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 , soyDocLoc...
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 ( ) ) ; } thi...
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 . isAssignable...
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...
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 . getStaticTagNameAsLowerC...
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 ...
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 . getOnlyEle...
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 : exprN...
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 suffi...
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 ( ) ; Exp...
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 ) { basicHas...
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 (...
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 ( soyTemp...
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 , variableMa...
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 ( finalStackTrac...
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 ] )...
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 ) ) {...
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 { re...
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 ) ) {...
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 . ...
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_STA...
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 [ ...
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 . shouldParen...
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 SoyMsgRa...
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 = nor...
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 ( reco...
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 ( new...
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 ( ) ...
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" ...
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 , ...
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 ( )...
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 ( ) ) ; checkIntCompariso...
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 ...
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 . u...
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 . appen...
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 ( ) + "=" ...
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 , de...
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 . toSourceS...
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 ?...
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 ( ) ; } thr...
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 ( ) instanc...
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 ( ) ) ;...
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 . D...
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 , "b...
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 . IN...
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 . typeDe...
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 ++ ) { arrayVisit...
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 . visitArr...
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 ( firstVarInstru...
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...
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 directiv...
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...
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 ( var...
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 alread...
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 ( ) . setR...
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 ( incrementa...
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 .