idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
30,600 | public T setId ( int id ) { Preconditions . checkState ( this . id == null ) ; this . id = id ; return ( T ) this ; } | Sets the id for the node to be built . |
30,601 | public T setSoyDoc ( String soyDoc , SourceLocation soyDocLocation ) { Preconditions . checkState ( this . soyDoc == null ) ; Preconditions . checkState ( cmdText != null ) ; int paramOffset = soyDoc . indexOf ( "@param" ) ; if ( paramOffset != - 1 ) { errorReporter . report ( new RawTextNode ( - 1 , soyDoc , soyDocLocation ) . substringLocation ( paramOffset , paramOffset + "@param" . length ( ) ) , SOYDOC_PARAM ) ; } this . soyDoc = soyDoc ; Preconditions . checkArgument ( soyDoc . startsWith ( "/**" ) && soyDoc . endsWith ( "*/" ) ) ; this . soyDocDesc = cleanSoyDocHelper ( soyDoc ) ; return ( T ) this ; } | Sets the SoyDoc for the node to be built . |
30,602 | public T addParams ( Iterable < ? extends TemplateParam > newParams ) { Set < String > seenParamKeys = new HashSet < > ( ) ; if ( this . params == null ) { this . params = ImmutableList . copyOf ( newParams ) ; } else { for ( TemplateParam oldParam : this . params ) { seenParamKeys . add ( oldParam . name ( ) ) ; } this . params = ImmutableList . < TemplateParam > builder ( ) . addAll ( this . params ) . addAll ( newParams ) . build ( ) ; } for ( TemplateParam param : newParams ) { if ( param . name ( ) . equals ( "ij" ) ) { errorReporter . report ( param . nameLocation ( ) , INVALID_PARAM_NAMED_IJ ) ; } if ( ! seenParamKeys . add ( param . name ( ) ) ) { errorReporter . report ( param . nameLocation ( ) , PARAM_ALREADY_DECLARED , param . name ( ) ) ; } } return ( T ) this ; } | This method is intended to be called at most once for header params . |
30,603 | public static < T extends Node > ImmutableList < T > getAllNodesOfType ( Node rootSoyNode , final Class < T > classObject ) { return getAllMatchingNodesOfType ( rootSoyNode , classObject , arg -> true ) ; } | Retrieves all nodes in a tree that are an instance of a particular class . |
30,604 | private static < T extends Node > ImmutableList < T > getAllMatchingNodesOfType ( Node rootSoyNode , final Class < T > classObject , final Predicate < T > filter ) { final ImmutableList . Builder < T > matchedNodesBuilder = ImmutableList . builder ( ) ; final boolean exploreExpressions = ExprNode . class . isAssignableFrom ( classObject ) ; visitAllNodes ( rootSoyNode , new NodeVisitor < Node , VisitDirective > ( ) { public VisitDirective exec ( Node node ) { if ( classObject . isInstance ( node ) ) { T typedNode = classObject . cast ( node ) ; if ( filter . test ( typedNode ) ) { matchedNodesBuilder . add ( typedNode ) ; } } if ( ! exploreExpressions && node instanceof ExprNode ) { return VisitDirective . SKIP_CHILDREN ; } return VisitDirective . CONTINUE ; } } ) ; return matchedNodesBuilder . build ( ) ; } | Retrieves all nodes in a tree that are an instance of a particular class and match the given predicate . |
30,605 | public static < R > void execOnAllV2Exprs ( SoyNode node , final AbstractNodeVisitor < ExprNode , R > exprNodeVisitor ) { visitAllNodes ( node , new NodeVisitor < Node , VisitDirective > ( ) { public VisitDirective exec ( Node node ) { if ( node instanceof ExprHolderNode ) { for ( ExprRootNode expr : ( ( ExprHolderNode ) node ) . getExprList ( ) ) { exprNodeVisitor . exec ( expr ) ; } } else if ( node instanceof ExprNode ) { return VisitDirective . SKIP_CHILDREN ; } return VisitDirective . CONTINUE ; } } ) ; } | Given a Soy node and a visitor for expression trees traverses the subtree of the node and executes the visitor on all expressions held by nodes in the subtree . |
30,606 | public static boolean checkCloseTagClosesOptional ( TagName closeTag , TagName optionalOpenTag ) { if ( ! optionalOpenTag . isStatic ( ) || ! optionalOpenTag . isDefinitelyOptional ( ) ) { return false ; } if ( ! closeTag . isStatic ( ) ) { return true ; } String openTagName = optionalOpenTag . getStaticTagNameAsLowerCase ( ) ; String closeTagName = closeTag . getStaticTagNameAsLowerCase ( ) ; checkArgument ( ! openTagName . equals ( closeTagName ) ) ; if ( "p" . equals ( openTagName ) ) { return ! PTAG_CLOSE_EXCEPTIONS . contains ( closeTagName ) ; } return OPTIONAL_TAG_CLOSE_TAG_RULES . containsEntry ( openTagName , closeTagName ) ; } | Checks if the an open tag can be auto - closed by a following close tag which does not have the same tag name as the open tag . |
30,607 | public static boolean checkOpenTagClosesOptional ( TagName openTag , TagName optionalOpenTag ) { checkArgument ( optionalOpenTag . isDefinitelyOptional ( ) , "Open tag is not optional." ) ; if ( ! ( openTag . isStatic ( ) && optionalOpenTag . isStatic ( ) ) ) { return false ; } String optionalTagName = optionalOpenTag . getStaticTagNameAsLowerCase ( ) ; String openTagName = openTag . getStaticTagNameAsLowerCase ( ) ; return OPTIONAL_TAG_OPEN_CLOSE_RULES . containsEntry ( optionalTagName , openTagName ) ; } | Checks if the given open tag can implicitly close the given optional tag . |
30,608 | public SwitchBuilder addCase ( Expression caseLabel , Statement body ) { clauses . add ( new Switch . CaseClause ( ImmutableList . of ( caseLabel ) , body ) ) ; return this ; } | Adds a case clause to this switch statement . |
30,609 | public ExprNode valueAsExpr ( ErrorReporter reporter ) { checkState ( value == null ) ; if ( valueExprList . size ( ) > 1 ) { reporter . report ( valueExprList . get ( 1 ) . getSourceLocation ( ) , EXPECTED_A_SINGLE_EXPRESSION , key . identifier ( ) ) ; return valueExprList . get ( 0 ) ; } return Iterables . getOnlyElement ( valueExprList ) ; } | Returns the value as an expression . Only call on an expression attribute . |
30,610 | public static List < String > genNoncollidingBaseNamesForExprs ( List < ExprNode > exprNodes , String fallbackBaseName , ErrorReporter errorReporter ) { int numExprs = exprNodes . size ( ) ; List < List < String > > candidateBaseNameLists = Lists . newArrayListWithCapacity ( numExprs ) ; for ( ExprNode exprRoot : exprNodes ) { candidateBaseNameLists . add ( genCandidateBaseNamesForExpr ( exprRoot ) ) ; } Multimap < String , ExprNode > collisionStrToLongestCandidatesMultimap = HashMultimap . create ( ) ; for ( int i = 0 ; i < numExprs ; i ++ ) { ExprNode exprRoot = exprNodes . get ( i ) ; List < String > candidateBaseNameList = candidateBaseNameLists . get ( i ) ; if ( candidateBaseNameList . isEmpty ( ) ) { continue ; } String longestCandidate = candidateBaseNameList . get ( candidateBaseNameList . size ( ) - 1 ) ; collisionStrToLongestCandidatesMultimap . put ( longestCandidate , exprRoot ) ; for ( int j = 0 , n = longestCandidate . length ( ) ; j < n ; j ++ ) { if ( longestCandidate . charAt ( j ) == '_' ) { collisionStrToLongestCandidatesMultimap . put ( longestCandidate . substring ( j + 1 ) , exprRoot ) ; } } } List < String > noncollidingBaseNames = Lists . newArrayListWithCapacity ( numExprs ) ; OUTER : for ( int i = 0 ; i < numExprs ; i ++ ) { List < String > candidateBaseNameList = candidateBaseNameLists . get ( i ) ; if ( ! candidateBaseNameList . isEmpty ( ) ) { for ( String candidateBaseName : candidateBaseNameList ) { if ( collisionStrToLongestCandidatesMultimap . get ( candidateBaseName ) . size ( ) == 1 ) { noncollidingBaseNames . add ( candidateBaseName ) ; continue OUTER ; } } ExprNode exprRoot = exprNodes . get ( i ) ; String longestCandidate = candidateBaseNameList . get ( candidateBaseNameList . size ( ) - 1 ) ; ExprNode collidingExprRoot = null ; for ( ExprNode er : collisionStrToLongestCandidatesMultimap . get ( longestCandidate ) ) { if ( er != exprRoot ) { collidingExprRoot = er ; break ; } } errorReporter . report ( collidingExprRoot . getSourceLocation ( ) , COLLIDING_EXPRESSIONS , exprRoot . toSourceString ( ) , collidingExprRoot . toSourceString ( ) ) ; return noncollidingBaseNames ; } else { noncollidingBaseNames . add ( fallbackBaseName ) ; } } return noncollidingBaseNames ; } | Generates base names for all the expressions in a list where for each expression we use the shortest candidate base name that does not collide with any of the candidate base names generated from other expressions in the list . Two candidate base names are considered to collide if they are identical or if one is a suffix of the other beginning after an underscore character . |
30,611 | public Expression build ( CodeChunk . Generator codeGenerator ) { ImmutableList < IfThenPair < Expression > > pairs = conditions . build ( ) ; Expression ternary = tryCreateTernary ( pairs ) ; if ( ternary != null ) { return ternary ; } VariableDeclaration decl = codeGenerator . declarationBuilder ( ) . build ( ) ; Expression var = decl . ref ( ) ; ConditionalBuilder builder = null ; for ( IfThenPair < Expression > oldCondition : pairs ) { Expression newConsequent = var . assign ( oldCondition . consequent ) ; if ( builder == null ) { builder = ifStatement ( oldCondition . predicate , newConsequent . asStatement ( ) ) ; } else { builder . addElseIf ( oldCondition . predicate , newConsequent . asStatement ( ) ) ; } } if ( trailingElse != null ) { builder . setElse ( var . assign ( trailingElse ) . asStatement ( ) ) ; } return var . withInitialStatements ( ImmutableList . of ( decl , builder . build ( ) ) ) ; } | Finishes building this conditional . |
30,612 | void addBasic ( Token token ) { if ( basicStart == - 1 ) { basicStart = buffer . length ( ) ; basicStartOfWhitespace = - 1 ; basicHasNewline = false ; } switch ( token . kind ) { case SoyFileParserConstants . TOKEN_WS : if ( token . image . indexOf ( '\r' ) != - 1 || token . image . indexOf ( '\n' ) != - 1 ) { basicHasNewline = true ; } if ( basicStartOfWhitespace == - 1 && whitespaceMode == WhitespaceMode . JOIN ) { basicStartOfWhitespace = buffer . length ( ) ; endLineAtStartOfWhitespace = offsets . endLine ( ) ; endColumnAtStartOfWhitespace = offsets . endColumn ( ) ; } break ; case SoyFileParserConstants . TOKEN_NOT_WS : maybeCollapseWhitespace ( token . image ) ; break ; default : throw new AssertionError ( SoyFileParserConstants . tokenImage [ token . kind ] + " is not a basic text token" ) ; } append ( token , token . image ) ; } | Append a basic token . Basic tokens are text literals . |
30,613 | private void append ( Token token , String content ) { if ( content . isEmpty ( ) ) { throw new IllegalStateException ( String . format ( "shouldn't append empty content: %s @ %s" , SoyFileParserConstants . tokenImage [ token . kind ] , Tokens . createSrcLoc ( fileName , token ) ) ) ; } boolean addOffset = false ; if ( offsets . isEmpty ( ) ) { addOffset = true ; } else if ( discontinuityReason != Reason . NONE ) { addOffset = true ; } else { if ( offsets . endLine ( ) == token . beginLine ) { if ( offsets . endColumn ( ) + 1 != token . beginColumn ) { addOffset = true ; discontinuityReason = Reason . COMMENT ; } } else if ( offsets . endLine ( ) + 1 == token . beginLine && token . beginColumn != 1 ) { addOffset = true ; discontinuityReason = Reason . COMMENT ; } } if ( addOffset ) { offsets . add ( buffer . length ( ) , token . beginLine , token . beginColumn , discontinuityReason ) ; discontinuityReason = Reason . NONE ; } offsets . setEndLocation ( token . endLine , token . endColumn ) ; buffer . append ( content ) ; } | updates the location with the given tokens location . |
30,614 | public static String javaClassNameFromSoyTemplateName ( String soyTemplate ) { checkArgument ( BaseUtils . isDottedIdentifier ( soyTemplate ) , "%s is not a valid template name." , soyTemplate ) ; return CLASS_PREFIX + soyTemplate ; } | Translate a user controlled Soy name to a form that is safe to encode in a java class method or field name . |
30,615 | public static String javaFileName ( String soyNamespace , String fileName ) { checkArgument ( BaseUtils . isDottedIdentifier ( soyNamespace ) , "%s is not a valid soy namspace name." , soyNamespace ) ; return ( CLASS_PREFIX + soyNamespace ) . replace ( '.' , '/' ) + '/' + fileName ; } | Given the soy namespace and file name returns the path where the corresponding resource should be stored . |
30,616 | public static void rewriteStackTrace ( Throwable throwable ) { StackTraceElement [ ] stack = throwable . getStackTrace ( ) ; for ( int i = 0 ; i < stack . length ; i ++ ) { StackTraceElement curr = stack [ i ] ; if ( curr . getClassName ( ) . startsWith ( CLASS_PREFIX ) ) { stack [ i ] = new StackTraceElement ( soyTemplateNameFromJavaClassName ( curr . getClassName ( ) ) , curr . getMethodName ( ) , curr . getFileName ( ) , curr . getLineNumber ( ) ) ; } } throwable . setStackTrace ( stack ) ; } | Rewrites the given stack trace by replacing all references to generated jbcsrc types with the original template names . |
30,617 | private static String translateVar ( SoyToJsVariableMappings variableMappings , Matcher matcher ) { Preconditions . checkArgument ( matcher . matches ( ) ) ; String firstPart = matcher . group ( 1 ) ; StringBuilder exprTextSb = new StringBuilder ( ) ; String translation = getLocalVarTranslation ( firstPart , variableMappings ) ; if ( translation != null ) { exprTextSb . append ( translation ) ; } else { exprTextSb . append ( "opt_data." ) . append ( firstPart ) ; } return exprTextSb . toString ( ) ; } | Helper function to translate a variable or data reference . |
30,618 | public String typeExprForRecordMember ( boolean isOptional ) { if ( typeExpressions . size ( ) > 1 || isOptional ) { return "(" + typeExpr ( ) + ( isOptional && ! typeExpressions . contains ( "undefined" ) ? "|undefined" : "" ) + ")" ; } return typeExpr ( ) ; } | Returns a type expression for a record member . In some cases this requires additional parens . |
30,619 | public static DictImpl forProviderMap ( Map < String , ? extends SoyValueProvider > providerMap , RuntimeMapTypeTracker . Type mapType ) { return new DictImpl ( providerMap , mapType ) ; } | Creates a SoyDict implementation for a particular underlying provider map . |
30,620 | private StackTraceElement [ ] concatWithJavaStackTrace ( StackTraceElement [ ] javaStackTrace ) { if ( soyStackTrace . isEmpty ( ) ) { return javaStackTrace ; } StackTraceElement [ ] finalStackTrace = new StackTraceElement [ soyStackTrace . size ( ) + javaStackTrace . length ] ; soyStackTrace . toArray ( finalStackTrace ) ; System . arraycopy ( javaStackTrace , 0 , finalStackTrace , soyStackTrace . size ( ) , javaStackTrace . length ) ; return finalStackTrace ; } | Prepend the soy stack trace to the given standard java stack trace . |
30,621 | public void put ( Object ... data ) { if ( data . length % 2 != 0 ) { throw new SoyDataException ( "Varargs to put(...) must have an even number of arguments (key-value pairs)." ) ; } for ( int i = 0 ; i < data . length ; i += 2 ) { try { put ( ( String ) data [ i ] , SoyData . createFromExistingData ( data [ i + 1 ] ) ) ; } catch ( ClassCastException cce ) { throw new SoyDataException ( "Attempting to add a mapping containing a non-string key (key type " + data [ i ] . getClass ( ) . getName ( ) + ")." ) ; } } } | Convenience function to put multiple mappings in one call . |
30,622 | public void remove ( String keyStr ) { List < String > keys = split ( keyStr , '.' ) ; int numKeys = keys . size ( ) ; CollectionData collectionData = this ; for ( int i = 0 ; i <= numKeys - 2 ; ++ i ) { SoyData soyData = collectionData . getSingle ( keys . get ( i ) ) ; if ( ! ( soyData instanceof CollectionData ) ) { return ; } collectionData = ( CollectionData ) soyData ; } collectionData . removeSingle ( keys . get ( numKeys - 1 ) ) ; } | Removes the data at the specified key string . |
30,623 | private static List < String > split ( String str , char delim ) { List < String > result = Lists . newArrayList ( ) ; int currPartStart = 0 ; while ( true ) { int currPartEnd = str . indexOf ( delim , currPartStart ) ; if ( currPartEnd == - 1 ) { result . add ( str . substring ( currPartStart ) ) ; break ; } else { result . add ( str . substring ( currPartStart , currPartEnd ) ) ; currPartStart = currPartEnd + 1 ; } } return result ; } | Splits a string into tokens at the specified delimiter . |
30,624 | public static boolean isNumericPrimitive ( SoyType type ) { SoyType . Kind kind = type . getKind ( ) ; if ( NUMERIC_PRIMITIVES . contains ( kind ) ) { return true ; } return type . isAssignableFrom ( NUMBER_TYPE ) || NUMBER_TYPE . isAssignableFrom ( type ) ; } | Returns true if the input type is a numeric primitive type such as int float proto enum and number . |
30,625 | public static SoyType tryRemoveNull ( SoyType soyType ) { if ( soyType == NullType . getInstance ( ) ) { return NullType . getInstance ( ) ; } return removeNull ( soyType ) ; } | If the type is nullable makes it non - nullable . |
30,626 | public static SoyType computeLowestCommonType ( SoyTypeRegistry typeRegistry , SoyType t0 , SoyType t1 ) { if ( t0 == ErrorType . getInstance ( ) || t1 == ErrorType . getInstance ( ) ) { return ErrorType . getInstance ( ) ; } if ( t0 . isAssignableFrom ( t1 ) ) { return t0 ; } else if ( t1 . isAssignableFrom ( t0 ) ) { return t1 ; } else { return typeRegistry . getOrCreateUnionType ( t0 , t1 ) ; } } | Compute the most specific type that is assignable from both t0 and t1 . |
30,627 | public static SoyType computeLowestCommonType ( SoyTypeRegistry typeRegistry , Collection < SoyType > types ) { SoyType result = null ; for ( SoyType type : types ) { result = ( result == null ) ? type : computeLowestCommonType ( typeRegistry , result , type ) ; } return result ; } | Compute the most specific type that is assignable from all types within a collection . |
30,628 | public static Optional < SoyType > computeLowestCommonTypeArithmetic ( SoyType t0 , SoyType t1 ) { if ( t0 . getKind ( ) == Kind . ERROR || t1 . getKind ( ) == Kind . ERROR ) { return Optional . of ( ErrorType . getInstance ( ) ) ; } if ( ! isNumericOrUnknown ( t0 ) || ! isNumericOrUnknown ( t1 ) ) { return Optional . absent ( ) ; } if ( t0 . isAssignableFrom ( t1 ) ) { return Optional . of ( t0 ) ; } else if ( t1 . isAssignableFrom ( t0 ) ) { return Optional . of ( t1 ) ; } else { return Optional . of ( FloatType . getInstance ( ) ) ; } } | Compute the most specific type that is assignable from both t0 and t1 taking into account arithmetic promotions - that is converting int to float if needed . |
30,629 | Statement detachForCall ( final Expression callRender ) { checkArgument ( callRender . resultType ( ) . equals ( RENDER_RESULT_TYPE ) ) ; final Label reattachRender = new Label ( ) ; final SaveRestoreState saveRestoreState = variables . saveRestoreState ( ) ; int state = addState ( reattachRender , Statement . NULL_STATEMENT ) ; final Statement saveState = stateField . putInstanceField ( thisExpr , BytecodeUtils . constant ( state ) ) ; return new Statement ( ) { protected void doGen ( CodeBuilder adapter ) { callRender . gen ( adapter ) ; adapter . dup ( ) ; MethodRef . RENDER_RESULT_IS_DONE . invokeUnchecked ( adapter ) ; Label end = new Label ( ) ; adapter . ifZCmp ( Opcodes . IFNE , end ) ; saveRestoreState . save ( ) . gen ( adapter ) ; saveState . gen ( adapter ) ; adapter . returnValue ( ) ; adapter . mark ( reattachRender ) ; callRender . gen ( adapter ) ; adapter . dup ( ) ; MethodRef . RENDER_RESULT_IS_DONE . invokeUnchecked ( adapter ) ; Label restore = new Label ( ) ; adapter . ifZCmp ( Opcodes . IFNE , restore ) ; adapter . returnValue ( ) ; adapter . mark ( restore ) ; saveRestoreState . restore ( ) . gen ( adapter ) ; adapter . mark ( end ) ; adapter . pop ( ) ; } } ; } | Generate detach logic for calls . |
30,630 | Statement generateReattachTable ( ) { final Expression readField = stateField . accessor ( thisExpr ) ; final Statement defaultCase = Statement . throwExpression ( MethodRef . RUNTIME_UNEXPECTED_STATE_ERROR . invoke ( readField ) ) ; return new Statement ( ) { protected void doGen ( final CodeBuilder adapter ) { int [ ] keys = new int [ reattaches . size ( ) ] ; for ( int i = 0 ; i < keys . length ; i ++ ) { keys [ i ] = i ; } readField . gen ( adapter ) ; adapter . tableSwitch ( keys , new TableSwitchGenerator ( ) { public void generateCase ( int key , Label end ) { if ( key == 0 ) { adapter . goTo ( end ) ; return ; } ReattachState reattachState = reattaches . get ( key ) ; reattachState . restoreStatement ( ) . gen ( adapter ) ; adapter . goTo ( reattachState . reattachPoint ( ) ) ; } public void generateDefault ( ) { defaultCase . gen ( adapter ) ; } } , true ) ; } } ; } | Returns a statement that generates the reattach jump table . |
30,631 | private int addState ( Label reattachPoint , Statement restore ) { ReattachState create = ReattachState . create ( reattachPoint , restore ) ; reattaches . add ( create ) ; int state = reattaches . size ( ) - 1 ; return state ; } | Add a new state item and return the state . |
30,632 | private boolean shouldProtect ( Expression operand , OperandPosition operandPosition ) { if ( operand instanceof Operation ) { Operation operation = ( Operation ) operand ; return operation . precedence ( ) < this . precedence ( ) || ( operation . precedence ( ) == this . precedence ( ) && operandPosition . shouldParenthesize ( operation . associativity ( ) ) ) ; } else if ( operand instanceof Leaf ) { JsExpr expr = ( ( Leaf ) operand ) . value ( ) ; return expr . getPrecedence ( ) < this . precedence ( ) ; } else { return false ; } } | An operand needs to be protected with parens if |
30,633 | public static SimplifyVisitor create ( IdGenerator idGenerator , ImmutableList < SoyFileNode > sourceFiles ) { return new SimplifyVisitor ( idGenerator , sourceFiles , new SimplifyExprVisitor ( ) , new PreevalVisitorFactory ( ) ) ; } | Creates a new simplify visitor . |
30,634 | static String buildMsgContentStrForMsgIdComputation ( ImmutableList < SoyMsgPart > msgParts , boolean doUseBracedPhs ) { msgParts = IcuSyntaxUtils . convertMsgPartsToEmbeddedIcuSyntax ( msgParts ) ; StringBuilder msgStrSb = new StringBuilder ( ) ; for ( SoyMsgPart msgPart : msgParts ) { if ( msgPart instanceof SoyMsgRawTextPart ) { msgStrSb . append ( ( ( SoyMsgRawTextPart ) msgPart ) . getRawText ( ) ) ; } else if ( msgPart instanceof SoyMsgPlaceholderPart ) { if ( doUseBracedPhs ) { msgStrSb . append ( '{' ) ; } msgStrSb . append ( ( ( SoyMsgPlaceholderPart ) msgPart ) . getPlaceholderName ( ) ) ; if ( doUseBracedPhs ) { msgStrSb . append ( '}' ) ; } } else { throw new AssertionError ( "unexpected child: " + msgPart ) ; } } return msgStrSb . toString ( ) ; } | Private helper to build the canonical message content string that should be used for msg id computation . |
30,635 | private static String formatParseExceptionDetails ( String errorToken , List < String > expectedTokens ) { ImmutableSet . Builder < String > normalizedTokensBuilder = ImmutableSet . builder ( ) ; for ( String t : expectedTokens ) { normalizedTokensBuilder . add ( maybeQuoteForParseError ( t ) ) ; } expectedTokens = normalizedTokensBuilder . build ( ) . asList ( ) ; StringBuilder details = new StringBuilder ( ) ; int numExpectedTokens = expectedTokens . size ( ) ; if ( numExpectedTokens != 0 ) { details . append ( ": expected " ) ; for ( int i = 0 ; i < numExpectedTokens ; i ++ ) { details . append ( expectedTokens . get ( i ) ) ; if ( i < numExpectedTokens - 2 ) { details . append ( ", " ) ; } if ( i == numExpectedTokens - 2 ) { if ( numExpectedTokens > 2 ) { details . append ( ',' ) ; } details . append ( " or " ) ; } } } return String . format ( "parse error at '%s'%s" , escapeWhitespaceForErrorPrinting ( errorToken ) , details . toString ( ) ) ; } | A helper method for formatting javacc ParseExceptions . |
30,636 | private static void maybeMarkBadProtoAccess ( ExprNode expr , SoyValue value ) { if ( value instanceof SoyProtoValue ) { ( ( SoyProtoValue ) value ) . setAccessLocationKey ( expr . getSourceLocation ( ) ) ; } } | If the value is a proto then set the current access location since we are about to access it incorrectly . |
30,637 | private static boolean isNullOrUndefinedBase ( SoyValue base ) { return base == null || base instanceof NullData || base instanceof UndefinedData || base == NullSafetySentinel . INSTANCE ; } | Returns true if the base SoyValue of a data access chain is null or undefined . |
30,638 | protected void visitFieldAccessNode ( FieldAccessNode node ) { visitChildren ( node ) ; ExprNode baseExpr = node . getChild ( 0 ) ; if ( baseExpr instanceof RecordLiteralNode ) { RecordLiteralNode recordLiteral = ( RecordLiteralNode ) baseExpr ; for ( int i = 0 ; i < recordLiteral . numChildren ( ) ; i ++ ) { if ( recordLiteral . getKey ( i ) . identifier ( ) . equals ( node . getFieldName ( ) ) ) { node . getParent ( ) . replaceChild ( node , recordLiteral . getChild ( i ) ) ; return ; } } } else if ( baseExpr instanceof ProtoInitNode ) { ProtoInitNode protoInit = ( ProtoInitNode ) baseExpr ; int fieldIndex = - 1 ; for ( int i = 0 ; i < protoInit . getParamNames ( ) . size ( ) ; i ++ ) { if ( protoInit . getParamNames ( ) . get ( i ) . identifier ( ) . equals ( node . getFieldName ( ) ) ) { fieldIndex = i ; break ; } } if ( fieldIndex != - 1 ) { node . getParent ( ) . replaceChild ( node , protoInit . getChild ( fieldIndex ) ) ; } else { } } } | this code since it desugars into a record literal . |
30,639 | private void attemptPreeval ( ExprNode node ) { SoyValue preevalResult ; try { preevalResult = preevalVisitor . exec ( node ) ; } catch ( RenderException e ) { return ; } PrimitiveNode newNode = InternalValueUtils . convertPrimitiveDataToExpr ( ( PrimitiveData ) preevalResult , node . getSourceLocation ( ) ) ; if ( newNode != null ) { node . getParent ( ) . replaceChild ( node , newNode ) ; } } | Attempts to preevaluate a node . If successful the node is replaced with a new constant node in the tree . If unsuccessful the tree is not changed . |
30,640 | static SoyValue getConstantOrNull ( ExprNode expr ) { switch ( expr . getKind ( ) ) { case NULL_NODE : return NullData . INSTANCE ; case BOOLEAN_NODE : return BooleanData . forValue ( ( ( BooleanNode ) expr ) . getValue ( ) ) ; case INTEGER_NODE : return IntegerData . forValue ( ( ( IntegerNode ) expr ) . getValue ( ) ) ; case FLOAT_NODE : return FloatData . forValue ( ( ( FloatNode ) expr ) . getValue ( ) ) ; case STRING_NODE : return StringData . forValue ( ( ( StringNode ) expr ) . getValue ( ) ) ; case GLOBAL_NODE : GlobalNode global = ( GlobalNode ) expr ; if ( global . isResolved ( ) ) { return getConstantOrNull ( global . getValue ( ) ) ; } return null ; default : return null ; } } | Returns the value of the given expression if it s constant else returns null . |
30,641 | public static < T > T visitField ( FieldDescriptor fieldDescriptor , FieldVisitor < T > visitor ) { if ( fieldDescriptor . isMapField ( ) ) { List < FieldDescriptor > mapFields = fieldDescriptor . getMessageType ( ) . getFields ( ) ; checkState ( mapFields . size ( ) == 2 , "proto representation of map fields changed" ) ; FieldDescriptor keyField = mapFields . get ( 0 ) ; FieldDescriptor valueField = mapFields . get ( 1 ) ; return visitor . visitMap ( fieldDescriptor , getScalarType ( keyField , visitor ) , getScalarType ( valueField , visitor ) ) ; } else if ( fieldDescriptor . isRepeated ( ) ) { return visitor . visitRepeated ( getScalarType ( fieldDescriptor , visitor ) ) ; } else { return getScalarType ( fieldDescriptor , visitor ) ; } } | Applies the visitor to the given field . |
30,642 | static JbcSrcJavaValue error ( Expression expr , JbcSrcValueErrorReporter reporter ) { return new JbcSrcJavaValue ( expr , null , null , false , true , reporter ) ; } | Constructs a JbcSrcJavaValue that represents an error . |
30,643 | static JbcSrcJavaValue of ( Expression expr , JbcSrcValueErrorReporter reporter ) { if ( expr instanceof SoyExpression ) { return new JbcSrcJavaValue ( expr , null , ( ( SoyExpression ) expr ) . soyType ( ) , false , false , reporter ) ; } return new JbcSrcJavaValue ( expr , null , null , false , false , reporter ) ; } | Constructs a JbcSrcJavaValue based on the Expression . |
30,644 | static JbcSrcJavaValue of ( Expression expr , Method method , JbcSrcValueErrorReporter reporter ) { checkNotNull ( method ) ; if ( expr instanceof SoyExpression ) { return new JbcSrcJavaValue ( expr , method , ( ( SoyExpression ) expr ) . soyType ( ) , false , false , reporter ) ; } return new JbcSrcJavaValue ( expr , method , null , false , false , reporter ) ; } | Constructs a JbcSrcJavaValue based on the Expression . The method is used to display helpful error messages to the user if necessary . It is not invoked . |
30,645 | static JbcSrcJavaValue of ( SoyExpression expr , SoyType allowedType , JbcSrcValueErrorReporter reporter ) { return new JbcSrcJavaValue ( expr , null , checkNotNull ( allowedType ) , false , false , reporter ) ; } | Constructs a JbcSrcJavaValue based on the Expression with the given SoyType as allowed types . The SoyType is expected to be based on the function signature so can be broader than the soy type of the expression itself . The expression is expected to be assignable to the type . |
30,646 | public static Class < ? > classFromAsmType ( Type type ) { Optional < Class < ? > > maybeClass = objectTypeToClassCache . getUnchecked ( type ) ; if ( ! maybeClass . isPresent ( ) ) { throw new IllegalArgumentException ( "Could not load: " + type ) ; } return maybeClass . get ( ) ; } | Returns the runtime class represented by the given type . |
30,647 | public static Expression numericConversion ( final Expression expr , final Type to ) { if ( to . equals ( expr . resultType ( ) ) ) { return expr ; } if ( ! isNumericPrimitive ( to ) || ! isNumericPrimitive ( expr . resultType ( ) ) ) { throw new IllegalArgumentException ( "Cannot convert from " + expr . resultType ( ) + " to " + to ) ; } return new Expression ( to , expr . features ( ) ) { protected void doGen ( CodeBuilder adapter ) { expr . gen ( adapter ) ; adapter . cast ( expr . resultType ( ) , to ) ; } } ; } | Returns an expression that does a numeric conversion cast from the given expression to the given type . |
30,648 | public static Expression compare ( final int comparisonOpcode , final Expression left , final Expression right ) { checkArgument ( left . resultType ( ) . equals ( right . resultType ( ) ) , "left and right must have matching types, found %s and %s" , left . resultType ( ) , right . resultType ( ) ) ; checkIntComparisonOpcode ( left . resultType ( ) , comparisonOpcode ) ; Features features = Expression . areAllCheap ( left , right ) ? Features . of ( Feature . CHEAP ) : Features . of ( ) ; return new Expression ( Type . BOOLEAN_TYPE , features ) { protected void doGen ( CodeBuilder mv ) { left . gen ( mv ) ; right . gen ( mv ) ; Label ifTrue = mv . newLabel ( ) ; Label end = mv . newLabel ( ) ; mv . ifCmp ( left . resultType ( ) , comparisonOpcode , ifTrue ) ; mv . pushBoolean ( false ) ; mv . goTo ( end ) ; mv . mark ( ifTrue ) ; mv . pushBoolean ( true ) ; mv . mark ( end ) ; } } ; } | Compares the two primitive valued expressions using the provided comparison operation . |
30,649 | public static Expression logicalNot ( final Expression baseExpr ) { baseExpr . checkAssignableTo ( Type . BOOLEAN_TYPE ) ; checkArgument ( baseExpr . resultType ( ) . equals ( Type . BOOLEAN_TYPE ) , "not a boolean expression" ) ; return new Expression ( Type . BOOLEAN_TYPE , baseExpr . features ( ) ) { protected void doGen ( CodeBuilder mv ) { baseExpr . gen ( mv ) ; Label ifTrue = mv . newLabel ( ) ; Label end = mv . newLabel ( ) ; mv . ifZCmp ( Opcodes . IFNE , ifTrue ) ; mv . pushBoolean ( true ) ; mv . goTo ( end ) ; mv . mark ( ifTrue ) ; mv . pushBoolean ( false ) ; mv . mark ( end ) ; } } ; } | Returns an expression that evaluates to the logical negation of the given boolean valued expression . |
30,650 | private static Expression doEqualsString ( SoyExpression stringExpr , SoyExpression other ) { SoyRuntimeType otherRuntimeType = other . soyRuntimeType ( ) ; if ( otherRuntimeType . isKnownStringOrSanitizedContent ( ) ) { if ( stringExpr . isNonNullable ( ) ) { return stringExpr . invoke ( MethodRef . EQUALS , other . unboxAsString ( ) ) ; } else { return MethodRef . OBJECTS_EQUALS . invoke ( stringExpr , other . unboxAsString ( ) ) ; } } if ( otherRuntimeType . isKnownNumber ( ) && other . isNonNullable ( ) ) { return MethodRef . RUNTIME_STRING_EQUALS_AS_NUMBER . invoke ( stringExpr , other . coerceToDouble ( ) ) ; } return MethodRef . RUNTIME_COMPARE_NULLABLE_STRING . invoke ( stringExpr , other . box ( ) ) ; } | Compare a string valued expression to another expression using soy == semantics . |
30,651 | public PyFunctionExprBuilder setUnpackedKwargs ( PyExpr mapping ) { if ( unpackedKwargs != null ) { throw new UnsupportedOperationException ( "Only one kwarg unpacking allowed per expression." ) ; } StringBuilder expr = new StringBuilder ( "**" ) ; if ( mapping . getPrecedence ( ) < Integer . MAX_VALUE ) { expr . append ( "(" ) . append ( mapping . getText ( ) ) . append ( ")" ) ; } else { expr . append ( mapping . getText ( ) ) ; } unpackedKwargs = expr . toString ( ) ; return this ; } | Unpacking keyword arguments will expand a dictionary into a series of keyword arguments . |
30,652 | public String build ( ) { StringBuilder sb = new StringBuilder ( funcName + "(" ) ; String args = argList . stream ( ) . map ( PyExpr :: getText ) . filter ( Objects :: nonNull ) . collect ( Collectors . joining ( ", " ) ) ; String kwargs = kwargMap . entrySet ( ) . stream ( ) . map ( entry -> entry . getKey ( ) + "=" + entry . getValue ( ) . getText ( ) ) . filter ( Objects :: nonNull ) . collect ( Collectors . joining ( ", " ) ) ; args = Strings . emptyToNull ( args ) ; kwargs = Strings . emptyToNull ( kwargs ) ; Joiner . on ( ", " ) . skipNulls ( ) . appendTo ( sb , args , kwargs , unpackedKwargs ) ; sb . append ( ")" ) ; return sb . toString ( ) ; } | Returns a valid Python function call as a String . |
30,653 | protected RenderVisitor createHelperInstance ( Appendable outputBuf , SoyRecord data ) { return new RenderVisitor ( evalVisitorFactory , outputBuf , basicTemplates , deltemplates , data , ijData , activeDelPackageSelector , msgBundle , xidRenamingMap , cssRenamingMap , debugSoyTemplateInfo , pluginInstances ) ; } | Creates a helper instance for rendering a subtemplate . |
30,654 | private void renderTemplate ( TemplateNode template , Predicate < String > paramsToTypeCheck ) { env = Environment . create ( template , data , ijData ) ; checkStrictParamTypes ( template , paramsToTypeCheck ) ; visitChildren ( template ) ; env = null ; } | A private helper to render templates with optimized type checking . |
30,655 | private SoyValue eval ( ExprNode expr , SoyNode node ) { if ( expr == null ) { throw RenderException . create ( "Cannot evaluate expression in V1 syntax." ) . addStackTraceElement ( node ) ; } if ( evalVisitor == null ) { evalVisitor = evalVisitorFactory . create ( env , cssRenamingMap , xidRenamingMap , msgBundle , debugSoyTemplateInfo , pluginInstances ) ; } try { return evalVisitor . exec ( expr ) ; } catch ( RenderException e ) { throw RenderException . createFromRenderException ( "When evaluating \"" + expr . toSourceString ( ) + "\": " + e . getMessage ( ) , e , node ) ; } catch ( Exception e ) { throw RenderException . createWithSource ( "When evaluating \"" + expr . toSourceString ( ) + "\": " + e . getMessage ( ) , e , node ) ; } } | Private helper to evaluate an expression . Always use this helper instead of using evalVisitor directly because this helper creates and throws a RenderException if there s an error . |
30,656 | static void append ( Appendable outputBuf , CharSequence cs ) { try { outputBuf . append ( cs ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } | Helper to append text to the output propagating any exceptions . |
30,657 | static void append ( Appendable outputBuf , SoyValue value , SoyNode node ) { try { value . render ( outputBuf ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } catch ( RenderException e ) { throw e . addStackTraceElement ( node ) ; } } | Helper to append a SoyValue to the output propagating any exceptions . |
30,658 | private SoyValue applyDirective ( SoyPrintDirective directive , SoyValue value , List < SoyValue > args , SoyNode node ) { if ( ! ( directive instanceof SoyJavaPrintDirective ) ) { throw RenderException . createWithSource ( "Failed to find Soy print directive with name '" + directive + "'" + " (tag " + node . toSourceString ( ) + ")" , node ) ; } if ( ! directive . getValidArgsSizes ( ) . contains ( args . size ( ) ) ) { throw RenderException . createWithSource ( "Print directive '" + directive + "' used with the wrong number of arguments (tag " + node . toSourceString ( ) + ")." , node ) ; } try { return ( ( SoyJavaPrintDirective ) directive ) . applyForJava ( value , args ) ; } catch ( RuntimeException e ) { throw RenderException . createWithSource ( String . format ( "Failed in applying directive '%s' in tag \"%s\" due to exception: %s" , directive , node . toSourceString ( ) , e . getMessage ( ) ) , e , node ) ; } } | Protected helper to apply a print directive . |
30,659 | private void checkValueType ( TemplateParam param , SoyValue value , TemplateNode node ) { if ( ! TofuTypeChecks . isInstance ( param . type ( ) , value , node . getSourceLocation ( ) ) ) { throw RenderException . createWithSource ( "Parameter type mismatch: attempt to bind value '" + ( value instanceof UndefinedData ? "(undefined)" : value ) + "' (a " + value . getClass ( ) . getSimpleName ( ) + ") to parameter '" + param . name ( ) + "' which has a declared type of '" + param . type ( ) + "'." , node ) ; } } | Check that the value matches the given param type . |
30,660 | public String getDescriptorExpression ( ) { Descriptor descriptor = typeDescriptor ; while ( descriptor . getContainingType ( ) != null ) { descriptor = descriptor . getContainingType ( ) ; } return JavaQualifiedNames . getQualifiedName ( descriptor ) + ".getDescriptor()" ; } | For ParseInfo generation return a string that represents the Java source expression for the static descriptor constant . |
30,661 | public String getNameForBackend ( SoyBackendKind backend ) { switch ( backend ) { case JS_SRC : return ProtoUtils . calculateQualifiedJsName ( typeDescriptor ) ; case TOFU : case JBC_SRC : return JavaQualifiedNames . getClassName ( typeDescriptor ) ; case PYTHON_SRC : throw new UnsupportedOperationException ( ) ; } throw new AssertionError ( backend ) ; } | Returns this proto s type name for the given backend . |
30,662 | protected void visitHtmlAttributeNode ( HtmlAttributeNode node ) { if ( ! node . hasValue ( ) ) { return ; } SourceLocation insertionLocation = node . getSourceLocation ( ) ; for ( FunctionNode function : SoyTreeUtils . getAllNodesOfType ( node , FunctionNode . class ) ) { if ( ! ( function . getSoyFunction ( ) instanceof LoggingFunction ) ) { continue ; } FunctionNode funcNode = new FunctionNode ( Identifier . create ( VeLogJsSrcLoggingFunction . NAME , insertionLocation ) , VeLogJsSrcLoggingFunction . INSTANCE , insertionLocation ) ; funcNode . addChild ( new StringNode ( function . getFunctionName ( ) , QuoteStyle . SINGLE , insertionLocation ) ) ; funcNode . addChild ( new ListLiteralNode ( function . getChildren ( ) , insertionLocation ) ) ; StandaloneNode attributeName = node . getChild ( 0 ) ; if ( attributeName instanceof RawTextNode ) { funcNode . addChild ( new StringNode ( ( ( RawTextNode ) attributeName ) . getRawText ( ) , QuoteStyle . SINGLE , insertionLocation ) ) ; } else { String varName = "$soy_logging_function_attribute_" + node . getId ( ) ; LetContentNode letNode = LetContentNode . forVariable ( nodeIdGen . genId ( ) , attributeName . getSourceLocation ( ) , varName , attributeName . getSourceLocation ( ) , null ) ; node . replaceChild ( attributeName , new PrintNode ( nodeIdGen . genId ( ) , insertionLocation , true , new VarRefNode ( letNode . getVar ( ) . name ( ) , insertionLocation , letNode . getVar ( ) ) , ImmutableList . of ( ) , ErrorReporter . exploding ( ) ) ) ; letNode . addChild ( attributeName ) ; node . getParent ( ) . addChild ( node . getParent ( ) . getChildIndex ( node ) , letNode ) ; funcNode . addChild ( new VarRefNode ( letNode . getVar ( ) . name ( ) , insertionLocation , letNode . getVar ( ) ) ) ; } PrintNode loggingFunctionAttribute = new PrintNode ( nodeIdGen . genId ( ) , insertionLocation , true , funcNode , ImmutableList . of ( ) , ErrorReporter . exploding ( ) ) ; int appendIndex = node . getParent ( ) . getChildIndex ( node ) + 1 ; node . getParent ( ) . addChild ( appendIndex , loggingFunctionAttribute ) ; HtmlAttributeValueNode placeHolder = new HtmlAttributeValueNode ( nodeIdGen . genId ( ) , insertionLocation , Quotes . DOUBLE ) ; placeHolder . addChild ( new RawTextNode ( nodeIdGen . genId ( ) , ( ( LoggingFunction ) function . getSoyFunction ( ) ) . getPlaceholder ( ) , insertionLocation ) ) ; node . replaceChild ( node . getChild ( 1 ) , placeHolder ) ; break ; } visitChildrenAllowingConcurrentModification ( node ) ; } | For HtmlAttributeNode that has a logging function as its value replace the logging function with its place holder and append a new data attribute that contains all the desired information that are used later by the runtime library . |
30,663 | public static SanitizedContent ordainAsSafe ( String value , ContentKind kind ) { return ordainAsSafe ( value , kind , kind . getDefaultDir ( ) ) ; } | Faithfully assumes the provided value is safe and marks it not to be re - escaped . The value s direction is assumed to be LTR for JS URI ATTRIBUTES and CSS content and otherwise unknown . |
30,664 | private void findProtoTypesRecurse ( SoyType type , SortedSet < String > protoTypes ) { switch ( type . getKind ( ) ) { case PROTO : protoTypes . add ( ( ( SoyProtoType ) type ) . getDescriptorExpression ( ) ) ; break ; case PROTO_ENUM : protoTypes . add ( ( ( SoyProtoEnumType ) type ) . getDescriptorExpression ( ) ) ; break ; case UNION : for ( SoyType member : ( ( UnionType ) type ) . getMembers ( ) ) { findProtoTypesRecurse ( member , protoTypes ) ; } break ; case LIST : { ListType listType = ( ListType ) type ; findProtoTypesRecurse ( listType . getElementType ( ) , protoTypes ) ; break ; } case MAP : case LEGACY_OBJECT_MAP : { AbstractMapType mapType = ( AbstractMapType ) type ; findProtoTypesRecurse ( mapType . getKeyType ( ) , protoTypes ) ; findProtoTypesRecurse ( mapType . getValueType ( ) , protoTypes ) ; break ; } case RECORD : { RecordType recordType = ( RecordType ) type ; for ( SoyType fieldType : recordType . getMembers ( ) . values ( ) ) { findProtoTypesRecurse ( fieldType , protoTypes ) ; } break ; } case VE : { VeType veType = ( VeType ) type ; if ( veType . getDataType ( ) . isPresent ( ) ) { SoyType soyType = typeRegistry . getType ( veType . getDataType ( ) . get ( ) ) ; if ( soyType . getKind ( ) == Kind . PROTO ) { protoTypes . add ( ( ( SoyProtoType ) soyType ) . getDescriptorExpression ( ) ) ; } } break ; } case ANY : case UNKNOWN : case ERROR : case NULL : case BOOL : case INT : case FLOAT : case STRING : case HTML : case ATTRIBUTES : case JS : case CSS : case URI : case TRUSTED_RESOURCE_URI : case VE_DATA : } } | Recursively search for protocol buffer types within the given type . |
30,665 | private static String buildTemplateNameForJavadoc ( SoyFileNode currSoyFile , TemplateMetadata template ) { StringBuilder resultSb = new StringBuilder ( ) ; if ( template . getSourceLocation ( ) . getFilePath ( ) . equals ( currSoyFile . getFilePath ( ) ) && template . getTemplateKind ( ) != TemplateMetadata . Kind . DELTEMPLATE ) { resultSb . append ( template . getTemplateName ( ) . substring ( template . getTemplateName ( ) . lastIndexOf ( '.' ) ) ) ; } else { switch ( template . getTemplateKind ( ) ) { case BASIC : case ELEMENT : resultSb . append ( template . getTemplateName ( ) ) ; break ; case DELTEMPLATE : resultSb . append ( template . getDelTemplateName ( ) ) ; if ( ! template . getDelTemplateVariant ( ) . isEmpty ( ) ) { resultSb . append ( ':' ) ; resultSb . append ( template . getDelTemplateVariant ( ) ) ; } break ; } } if ( template . getVisibility ( ) != Visibility . PUBLIC ) { resultSb . append ( " (private)" ) ; } if ( template . getTemplateKind ( ) == TemplateMetadata . Kind . DELTEMPLATE ) { resultSb . append ( " (delegate)" ) ; } return resultSb . toString ( ) ; } | Private helper to build the human - readable string for referring to a template in the generated code s javadoc . |
30,666 | private static void appendImmutableList ( IndentedLinesBuilder ilb , String typeParamSnippet , Collection < String > itemSnippets ) { appendListOrSetHelper ( ilb , "ImmutableList." + typeParamSnippet + "of" , itemSnippets ) ; } | Private helper to append an ImmutableList to the code . |
30,667 | private static void appendImmutableMap ( IndentedLinesBuilder ilb , String typeParamSnippet , Map < String , String > entrySnippetPairs ) { if ( entrySnippetPairs . isEmpty ( ) ) { ilb . appendLineStart ( "ImmutableMap." , typeParamSnippet , "of()" ) ; } else { ilb . appendLine ( "ImmutableMap." , typeParamSnippet , "builder()" ) ; for ( Map . Entry < String , String > entrySnippetPair : entrySnippetPairs . entrySet ( ) ) { ilb . appendLine ( " .put(" , entrySnippetPair . getKey ( ) , ", " , entrySnippetPair . getValue ( ) , ")" ) ; } ilb . appendLineStart ( " .build()" ) ; } } | Private helper to append an ImmutableMap to the code . |
30,668 | static Environment create ( TemplateNode template , SoyRecord data , SoyRecord ijData ) { return new Impl ( template , data , ijData ) ; } | The main way to create an environment . |
30,669 | public static Iterable < CrossLanguageStringXform > getAllEscapers ( ) { return ImmutableList . of ( EscapeHtml . INSTANCE , NormalizeHtml . INSTANCE , EscapeHtmlNospace . INSTANCE , NormalizeHtmlNospace . INSTANCE , EscapeJsString . INSTANCE , EscapeJsRegex . INSTANCE , EscapeCssString . INSTANCE , FilterCssValue . INSTANCE , EscapeUri . INSTANCE , NormalizeUri . INSTANCE , FilterNormalizeUri . INSTANCE , FilterNormalizeMediaUri . INSTANCE , FilterImageDataUri . INSTANCE , FilterSipUri . INSTANCE , FilterSmsUri . INSTANCE , FilterTelUri . INSTANCE , FilterHtmlAttributes . INSTANCE , FilterHtmlElementName . INSTANCE ) ; } | An accessor for all string transforms defined above . |
30,670 | public static Statement returnExpression ( final Expression expression ) { return new Statement ( ) { protected void doGen ( CodeBuilder adapter ) { expression . gen ( adapter ) ; adapter . returnValue ( ) ; } } ; } | Generates a statement that returns the value produced by the given expression . |
30,671 | public static Statement throwExpression ( final Expression expression ) { expression . checkAssignableTo ( THROWABLE_TYPE ) ; return new Statement ( ) { protected void doGen ( CodeBuilder adapter ) { expression . gen ( adapter ) ; adapter . throwException ( ) ; } } ; } | Generates a statement that throws the throwable produced by the given expression . |
30,672 | public static Statement concat ( final Iterable < ? extends Statement > statements ) { checkNotNull ( statements ) ; return new Statement ( ) { protected void doGen ( CodeBuilder adapter ) { for ( Statement statement : statements ) { statement . gen ( adapter ) ; } } } ; } | Returns a statement that concatenates all the provided statements . |
30,673 | public final Statement labelStart ( final Label label ) { return new Statement ( ) { protected void doGen ( CodeBuilder adapter ) { adapter . mark ( label ) ; Statement . this . gen ( adapter ) ; } } ; } | Returns a new statement identical to this one but with the given label applied at the start of the statement . |
30,674 | final Expression then ( final Expression expression ) { return new Expression ( expression . resultType ( ) , expression . features ( ) ) { protected void doGen ( CodeBuilder adapter ) { Statement . this . gen ( adapter ) ; expression . gen ( adapter ) ; } } ; } | Returns an Expression that evaluates this statement followed by the given expression . |
30,675 | public Future < ? > future ( ) { Future < ? > f = future ; if ( f == null ) { throw new IllegalStateException ( "Result.future() can only be called if type() is DETACH, type was: " + type ) ; } return f ; } | Returns the future that soy is waiting for . |
30,676 | public void write ( T instance , ClassVisitor visitor ) { doWrite ( instance , visitor . visitAnnotation ( typeDescriptor , isRuntimeVisible ) ) ; } | Writes the given annotation to the visitor . |
30,677 | private static < T extends Annotation > FieldWriter annotationFieldWriter ( final String name , final AnnotationRef < T > ref ) { return new FieldWriter ( ) { public void write ( AnnotationVisitor visitor , Object value ) { ref . doWrite ( ref . annType . cast ( value ) , visitor . visitAnnotation ( name , ref . typeDescriptor ) ) ; } } ; } | Writes an annotation valued field to the writer . |
30,678 | private static FieldWriter simpleFieldWriter ( final String name ) { return new FieldWriter ( ) { public void write ( AnnotationVisitor visitor , Object value ) { visitor . visit ( name , value ) ; } } ; } | Writes an primitive valued field to the writer . |
30,679 | private static FieldWriter simpleArrayFieldWriter ( final String name ) { return new FieldWriter ( ) { public void write ( AnnotationVisitor visitor , Object value ) { int len = Array . getLength ( value ) ; AnnotationVisitor arrayVisitor = visitor . visitArray ( name ) ; for ( int i = 0 ; i < len ; i ++ ) { arrayVisitor . visit ( null , Array . get ( value , i ) ) ; } arrayVisitor . visitEnd ( ) ; } } ; } | Writes an simple array valued field to the annotation visitor . |
30,680 | private static < T extends Annotation > FieldWriter annotationArrayFieldWriter ( final String name , final AnnotationRef < T > ref ) { return new FieldWriter ( ) { public void write ( AnnotationVisitor visitor , Object value ) { int len = Array . getLength ( value ) ; AnnotationVisitor arrayVisitor = visitor . visitArray ( name ) ; for ( int i = 0 ; i < len ; i ++ ) { ref . doWrite ( ref . annType . cast ( Array . get ( value , i ) ) , arrayVisitor . visitAnnotation ( null , ref . typeDescriptor ) ) ; } arrayVisitor . visitEnd ( ) ; } } ; } | Writes an annotation array valued field to the annotation visitor . |
30,681 | public static LocalVariable createThisVar ( TypeInfo owner , Label start , Label end ) { return new LocalVariable ( "this" , owner . type ( ) , 0 , start , end , Feature . NON_NULLABLE ) ; } | parameters to tableEntry? |
30,682 | public void tableEntry ( CodeBuilder mv ) { mv . visitLocalVariable ( variableName ( ) , resultType ( ) . getDescriptor ( ) , null , start ( ) , end ( ) , index ( ) ) ; } | Write a local variable table entry for this variable . This informs debuggers about variable names types and lifetime . |
30,683 | private Statement store ( final Expression expr , final Optional < Label > firstVarInstruction ) { expr . checkAssignableTo ( resultType ( ) ) ; return new Statement ( ) { protected void doGen ( CodeBuilder adapter ) { expr . gen ( adapter ) ; if ( firstVarInstruction . isPresent ( ) ) { adapter . mark ( firstVarInstruction . get ( ) ) ; } adapter . visitVarInsn ( resultType ( ) . getOpcode ( Opcodes . ISTORE ) , index ( ) ) ; } } ; } | Writes the value at the top of the stack to the local variable . |
30,684 | public static SoyValue resolveSoyValueProvider ( SoyValueProvider provider ) { SoyValue value = provider . resolve ( ) ; return handleTofuNull ( value ) ; } | Helper function to translate NullData - > null when resolving a SoyValueProvider . |
30,685 | public static SoyString checkSoyString ( Object o ) { if ( o instanceof SoyString && o instanceof SanitizedContent && ( ( SanitizedContent ) o ) . getContentKind ( ) != ContentKind . TEXT && logger . isLoggable ( Level . WARNING ) ) { logger . log ( Level . WARNING , String . format ( "Passing in sanitized content into a template that accepts only string is forbidden. " + " Please modify the template to take in %s." , ( ( SanitizedContent ) o ) . getContentKind ( ) ) , new Exception ( ) ) ; } return ( SoyString ) o ; } | Casts the given type to SoyString or throws a ClassCastException . |
30,686 | public static SoyValue callLegacySoyFunction ( LegacyFunctionAdapter fnAdapter , List < SoyValue > args ) { for ( int i = 0 ; i < args . size ( ) ; i ++ ) { if ( args . get ( i ) == null ) { args . set ( i , NullData . INSTANCE ) ; } } return handleTofuNull ( fnAdapter . computeForJava ( args ) ) ; } | Helper function to translate null - > NullData when calling LegacyFunctionAdapters that may expect it . |
30,687 | public static SoyValue applyPrintDirective ( SoyJavaPrintDirective directive , SoyValue value , List < SoyValue > args ) { value = value == null ? NullData . INSTANCE : value ; for ( int i = 0 ; i < args . size ( ) ; i ++ ) { if ( args . get ( i ) == null ) { args . set ( i , NullData . INSTANCE ) ; } } return directive . applyForJava ( value , args ) ; } | Helper function to translate null - > NullData when calling SoyJavaPrintDirectives that may expect it . |
30,688 | public static CompiledTemplate applyEscapers ( CompiledTemplate delegate , ImmutableList < SoyJavaPrintDirective > directives ) { ContentKind kind = delegate . kind ( ) ; if ( canSkipEscaping ( directives , kind ) ) { return delegate ; } return new EscapedCompiledTemplate ( delegate , directives , kind ) ; } | Wraps a given template with a collection of escapers to apply . |
30,689 | PyStringExpr getPyExpr ( ) { if ( this . msgNode . isPlrselMsg ( ) ) { return this . msgNode . isPluralMsg ( ) ? pyFuncForPluralMsg ( ) : pyFuncForSelectMsg ( ) ; } else { return this . msgNode . isRawTextMsg ( ) ? pyFuncForRawTextMsg ( ) : pyFuncForGeneralMsg ( ) ; } } | Return the PyStringExpr for the render function call because we know render always return a string in Python runtime . |
30,690 | private Map < PyExpr , PyExpr > collectVarNameListAndToPyExprMap ( ) { Map < PyExpr , PyExpr > nodePyVarToPyExprMap = new LinkedHashMap < > ( ) ; for ( Map . Entry < String , MsgSubstUnitNode > entry : msgNode . getVarNameToRepNodeMap ( ) . entrySet ( ) ) { MsgSubstUnitNode substUnitNode = entry . getValue ( ) ; PyExpr substPyExpr = null ; if ( substUnitNode instanceof MsgPlaceholderNode ) { SoyNode phInitialNode = ( ( AbstractParentSoyNode < ? > ) substUnitNode ) . getChild ( 0 ) ; if ( phInitialNode instanceof PrintNode || phInitialNode instanceof CallNode || phInitialNode instanceof RawTextNode ) { substPyExpr = PyExprUtils . concatPyExprs ( genPyExprsVisitor . exec ( phInitialNode ) ) . toPyString ( ) ; } if ( phInitialNode instanceof MsgHtmlTagNode ) { substPyExpr = PyExprUtils . concatPyExprs ( genPyExprsVisitor . execOnChildren ( ( ParentSoyNode < ? > ) phInitialNode ) ) . toPyString ( ) ; } } else if ( substUnitNode instanceof MsgPluralNode ) { substPyExpr = translateToPyExprVisitor . exec ( ( ( MsgPluralNode ) substUnitNode ) . getExpr ( ) ) ; } else if ( substUnitNode instanceof MsgSelectNode ) { substPyExpr = translateToPyExprVisitor . exec ( ( ( MsgSelectNode ) substUnitNode ) . getExpr ( ) ) ; } if ( substPyExpr != null ) { nodePyVarToPyExprMap . put ( new PyStringExpr ( "'" + entry . getKey ( ) + "'" ) , substPyExpr ) ; } } return nodePyVarToPyExprMap ; } | Private helper to process and collect all variables used within this msg node for code generation . |
30,691 | Expression genCodeForParamAccess ( String paramName , VarDefn varDefn ) { Expression source = OPT_DATA ; if ( varDefn . isInjected ( ) ) { if ( paramName . equals ( CSP_NONCE_VARIABLE_NAME ) ) { return OPT_IJ_DATA . and ( OPT_IJ_DATA . dotAccess ( paramName ) , codeGenerator ) ; } source = OPT_IJ_DATA ; } else if ( varDefn . kind ( ) == VarDefn . Kind . STATE ) { return genCodeForStateAccess ( paramName , ( TemplateStateVar ) varDefn ) ; } return source . dotAccess ( paramName ) ; } | Method that returns code to access a named parameter . |
30,692 | protected Expression visitVarRefNode ( VarRefNode node ) { Expression translation = variableMappings . maybeGet ( node . getName ( ) ) ; if ( translation != null ) { return translation ; } else { return genCodeForParamAccess ( node . getName ( ) , node . getDefnDecl ( ) ) ; } } | Implementations for data references . |
30,693 | NullSafeAccumulator dotAccess ( FieldAccess access , boolean nullSafe ) { if ( access instanceof ProtoCall ) { ProtoCall protoCall = ( ProtoCall ) access ; Expression maybeUnpack = protoCall . unpackFunction ( ) ; if ( maybeUnpack != null ) { Preconditions . checkState ( unpackFunction == null , "this chain will already unpack with %s" , unpackFunction ) ; unpackFunction = maybeUnpack ; accessType = protoCall . accessType ( ) ; } } chain . add ( access . toChainAccess ( nullSafe ) ) ; return this ; } | Extends the access chain with a dot access to the given value . |
30,694 | NullSafeAccumulator bracketAccess ( Expression arg , boolean nullSafe ) { chain . add ( new Bracket ( arg , nullSafe ) ) ; accessType = AccessType . SINGULAR ; return this ; } | Extends the access chain with a bracket access to the given value . |
30,695 | Expression result ( CodeChunk . Generator codeGenerator ) { Expression accessChain = buildAccessChain ( base , codeGenerator , chain . iterator ( ) ) ; if ( unpackFunction == null ) { return accessChain ; } else { return accessType . unpackResult ( accessChain , unpackFunction ) ; } } | Returns a code chunk representing the entire access chain . Null - safe accesses in the chain generate code to make sure the chain is non - null before performing the access . |
30,696 | private static Expression buildAccessChain ( Expression base , CodeChunk . Generator generator , Iterator < ChainAccess > chain ) { if ( ! chain . hasNext ( ) ) { return base ; } ChainAccess link = chain . next ( ) ; if ( link . nullSafe ) { if ( ! base . isCheap ( ) ) { base = generator . declarationBuilder ( ) . setRhs ( base ) . build ( ) . ref ( ) ; } return ifExpression ( base . doubleEqualsNull ( ) , LITERAL_NULL ) . setElse ( buildAccessChain ( link . extend ( base ) , generator , chain ) ) . build ( generator ) ; } return buildAccessChain ( link . extend ( base ) , generator , chain ) ; } | Builds the access chain . |
30,697 | public static boolean isRtlLanguage ( String locale ) { try { return UScript . isRightToLeft ( UCharacter . getPropertyValueEnum ( UProperty . SCRIPT , ULocale . addLikelySubtags ( new ULocale ( locale ) ) . getScript ( ) ) ) ; } catch ( IllegalArgumentException e ) { return false ; } } | Returns whether a locale given as a string in the ICU syntax is RTL . |
30,698 | public List < String > genJsSrc ( SoyFileSetNode soyTree , TemplateRegistry registry , SoyIncrementalDomSrcOptions options , ErrorReporter errorReporter ) { SoyJsSrcOptions incrementalJSSrcOptions = options . toJsSrcOptions ( ) ; BidiGlobalDir bidiGlobalDir = SoyBidiUtils . decodeBidiGlobalDirFromJsOptions ( incrementalJSSrcOptions . getBidiGlobalDir ( ) , incrementalJSSrcOptions . getUseGoogIsRtlForBidiGlobalDir ( ) ) ; try ( SoyScopedData . InScope inScope = apiCallScope . enter ( null , bidiGlobalDir ) ) { new HtmlContextVisitor ( ) . exec ( soyTree ) ; if ( errorReporter . hasErrors ( ) ) { return Collections . emptyList ( ) ; } UnescapingVisitor . unescapeRawTextInHtml ( soyTree ) ; new RemoveUnnecessaryEscapingDirectives ( bidiGlobalDir ) . run ( soyTree ) ; new CombineConsecutiveRawTextNodesPass ( ) . run ( soyTree ) ; return createVisitor ( incrementalJSSrcOptions , registry , typeRegistry , inScope . getBidiGlobalDir ( ) , errorReporter ) . gen ( soyTree , registry , errorReporter ) ; } } | Generates Incremental DOM JS source code given a Soy parse tree an options object and an optional bundle of translated messages . |
30,699 | public static SanitizedContent serializeObject ( Gson gson , Object obj ) { return ordainJson ( gson . toJson ( obj ) ) ; } | Generate sanitized js content with provided Gson serializer . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.