private MethodSpec buildRuleMethod ( String methodName , PluralData data , Map < String , FieldSpec > fieldMap ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( methodName ) . addModifiers ( PRIVATE , STATIC ) . addParameter ( NUMBER_OPERANDS , "o" ) . returns ( PLURAL_CATEGORY ) ; for ( Map . Entry < String , PluralData . Rule > entry : data . rules ( ) . entrySet ( ) ) { String category = entry . getKey ( ) ; // Other is always the last condition in a set of rules. if ( category . equals ( "other" ) ) { // Last condition. method . addStatement ( "return PluralCategory.OTHER" ) ; break ; } // Create a representation of the full rule for commenting. PluralData . Rule rule = entry . getValue ( ) ; String ruleRepr = PluralRulePrinter . print ( rule . condition ) ; // Append all of the lambda methods we'll be invoking to evaluate this rule. List < String > fields = new ArrayList <> ( ) ; for ( Node < PluralType > condition : rule . condition . asStruct ( ) . nodes ( ) ) { String repr = PluralRulePrinter . print ( condition ) ; fields . add ( fieldMap . get ( repr ) . name ) ; } // Header comment to indicate which conditions are evaluated. method . addComment ( " $L" , ruleRepr ) ; if ( ! Objects . equals ( rule . sample , "" ) ) { List < String > samples = Splitter . on ( "@" ) . splitToList ( rule . sample ) ; for ( String sample : samples ) { method . addComment ( " $L" , sample ) ; } } // Emit the chain of OR conditions. If one is true we return the current category. int size = fields . size ( ) ; String stmt = "if (" ; for ( int i = 0 ; i < size ; i ++ ) { if ( i > 0 ) { stmt += " || " ; } stmt += fields . get ( i ) + ".eval(o)" ; } stmt += ")" ; // If the rule evaluates to true, return the associated plural category. method . beginControlFlow ( stmt ) ; method . addStatement ( "return PluralCategory." + category . toUpperCase ( ) ) ; method . endControlFlow ( ) ; method . addCode ( "\n" ) ; } return method . build ( ) ; }
Builds a method that when called evaluates the rule and returns a PluralCategory .