idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
30,400
private PyExpr escapeCall ( String callExpr , ImmutableList < SoyPrintDirective > directives ) { PyExpr escapedExpr = new PyExpr ( callExpr , Integer . MAX_VALUE ) ; if ( directives . isEmpty ( ) ) { return escapedExpr ; } // Successively wrap each escapedExpr in various directives. for ( SoyPrintDirective directive : directives ) { Preconditions . checkState ( directive instanceof SoyPySrcPrintDirective , "Autoescaping produced a bogus directive: %s" , directive . getName ( ) ) ; escapedExpr = ( ( SoyPySrcPrintDirective ) directive ) . applyForPySrc ( escapedExpr , ImmutableList . of ( ) ) ; } return escapedExpr ; }
Escaping directives might apply to the output of the call node so wrap the output with all required directives .
169
21
30,401
static String getLocalTemplateName ( TemplateNode node ) { String templateName = node . getPartialTemplateName ( ) . substring ( 1 ) ; if ( node . getVisibility ( ) == Visibility . PRIVATE ) { return "__" + templateName ; } return templateName ; }
Returns the python name for the template . Suitable for calling within the same module .
64
17
30,402
void checkConformance ( ) { resetErrorReporter ( ) ; // to check conformance we only need to run as much as it takes to execute the SoyConformance // pass. parse ( passManagerBuilder ( ) // We have to set disableAllTypeChecking to make sure default parameter types don't // break calculating TemplateMetadata objects. This is because SoyConformancePass runs // before ResolveExpressionTypesPass which normally populates the parameter types for // default params. With disableAllTypeChecking set an earlier pass will just set those // types to unknown // TODO(lukes): change the pass continuation mechanism to avoid generating a template // registry if we halt prior to cross template passes. . disableAllTypeChecking ( ) . addPassContinuationRule ( SoyConformancePass . class , PassContinuationRule . STOP_AFTER_PASS ) ) ; throwIfErrorsPresent ( ) ; reportWarnings ( ) ; }
A simple tool to enforce conformance and only conformance .
197
12
30,403
public void extractAndWriteMsgs ( SoyMsgBundleHandler msgBundleHandler , OutputFileOptions options , ByteSink output ) throws IOException { resetErrorReporter ( ) ; SoyMsgBundle bundle = doExtractMsgs ( ) ; msgBundleHandler . writeExtractedMsgs ( bundle , options , output , errorReporter ) ; throwIfErrorsPresent ( ) ; reportWarnings ( ) ; }
Extracts all messages from this Soy file set and writes the messages to an output sink .
91
19
30,404
private SoyMsgBundle doExtractMsgs ( ) { // extractMsgs disables a bunch of passes since it is typically not configured with things // like global definitions, type definitions, plugins, etc. SoyFileSetNode soyTree = parse ( passManagerBuilder ( ) . allowUnknownGlobals ( ) . allowV1Expression ( ) . setTypeRegistry ( SoyTypeRegistry . DEFAULT_UNKNOWN ) // TODO(lukes): consider changing this to pass a null resolver instead of the // ALLOW_UNDEFINED mode . setPluginResolver ( new PluginResolver ( PluginResolver . Mode . ALLOW_UNDEFINED , printDirectives , soyFunctionMap , soySourceFunctionMap , errorReporter ) ) . disableAllTypeChecking ( ) , // override the type registry so that the parser doesn't report errors when it // can't resolve strict types SoyTypeRegistry . DEFAULT_UNKNOWN ) . fileSet ( ) ; throwIfErrorsPresent ( ) ; SoyMsgBundle bundle = new ExtractMsgsVisitor ( ) . exec ( soyTree ) ; throwIfErrorsPresent ( ) ; return bundle ; }
Performs the parsing and extraction logic .
249
8
30,405
private ServerCompilationPrimitives compileForServerRendering ( ) { ParseResult result = parse ( ) ; throwIfErrorsPresent ( ) ; SoyFileSetNode soyTree = result . fileSet ( ) ; TemplateRegistry registry = result . registry ( ) ; // Clear the SoyDoc strings because they use unnecessary memory, unless we have a cache, in // which case it is pointless. if ( cache == null ) { new ClearSoyDocStringsVisitor ( ) . exec ( soyTree ) ; } throwIfErrorsPresent ( ) ; return new ServerCompilationPrimitives ( registry , soyTree ) ; }
Runs common compiler logic shared by tofu and jbcsrc backends .
132
16
30,406
public List < String > compileToIncrementalDomSrc ( SoyIncrementalDomSrcOptions jsSrcOptions ) { resetErrorReporter ( ) ; // For incremental dom backend, we don't desugar HTML nodes since it requires HTML context. ParseResult result = parse ( passManagerBuilder ( ) . desugarHtmlNodes ( false ) ) ; throwIfErrorsPresent ( ) ; List < String > generatedSrcs = new IncrementalDomSrcMain ( scopedData . enterable ( ) , typeRegistry ) . genJsSrc ( result . fileSet ( ) , result . registry ( ) , jsSrcOptions , errorReporter ) ; throwIfErrorsPresent ( ) ; reportWarnings ( ) ; return generatedSrcs ; }
Compiles this Soy file set into iDOM source code files and returns these JS files as a list of strings one per file .
165
26
30,407
void compileToPySrcFiles ( String outputPathFormat , SoyPySrcOptions pySrcOptions ) throws IOException { resetErrorReporter ( ) ; ParseResult result = parse ( ) ; throwIfErrorsPresent ( ) ; new PySrcMain ( scopedData . enterable ( ) ) . genPyFiles ( result . fileSet ( ) , pySrcOptions , outputPathFormat , errorReporter ) ; throwIfErrorsPresent ( ) ; reportWarnings ( ) ; }
Compiles this Soy file set into Python source code files and writes these Python files to disk .
108
19
30,408
ParseResult compileMinimallyForHeaders ( ) { resetErrorReporter ( ) ; ParseResult result = parse ( passManagerBuilder ( ) // ResolveExpressionTypesPass resolve types (specifically on default parameter // values) which is necessary for template metadatas . addPassContinuationRule ( ResolveExpressionTypesPass . class , PassContinuationRule . STOP_AFTER_PASS ) . allowV1Expression ( ) , typeRegistry ) ; throwIfErrorsPresent ( ) ; reportWarnings ( ) ; return result ; }
Performs the minimal amount of work needed to calculate TemplateMetadata objects for header compilation .
120
18
30,409
private void reportWarnings ( ) { ImmutableList < SoyError > warnings = errorReporter . getWarnings ( ) ; if ( warnings . isEmpty ( ) ) { return ; } // this is a custom feature used by the integration test suite. if ( generalOptions . getExperimentalFeatures ( ) . contains ( "testonly_throw_on_warnings" ) ) { errorReporter = null ; throw new SoyCompilationException ( warnings ) ; } String formatted = SoyErrors . formatErrors ( warnings ) ; if ( warningSink != null ) { try { warningSink . append ( formatted ) ; } catch ( IOException ioe ) { System . err . println ( "error while printing warnings" ) ; ioe . printStackTrace ( ) ; } } else { logger . warning ( formatted ) ; } }
Reports warnings ot the user configured warning sink . Should be called at the end of successful compiles .
180
20
30,410
@ SuppressWarnings ( "unchecked" ) // If a.equals(b) then a and b have the same type. public synchronized < T > T intern ( T value ) { Preconditions . checkNotNull ( value ) ; // Use a pseudo-random number generator to mix up the high and low bits of the hash code. Random generator = new java . util . Random ( value . hashCode ( ) ) ; int tries = 0 ; while ( true ) { int index = generator . nextInt ( table . length ) ; Object candidate = table [ index ] ; if ( candidate == null ) { // Found a good place to hash it. count ++ ; collisions += tries ; table [ index ] = value ; rehashIfNeeded ( ) ; return value ; } if ( candidate . equals ( value ) ) { Preconditions . checkArgument ( value . getClass ( ) == candidate . getClass ( ) , "Interned objects are equals() but different classes: %s and %s" , value , candidate ) ; return ( T ) candidate ; } tries ++ ; } }
Returns either the input or an instance that equals it that was previously passed to this method .
232
18
30,411
@ GuardedBy ( "this" ) private void rehashIfNeeded ( ) { int currentSize = table . length ; if ( currentSize - count >= currentSize / ( MAX_EXPECTED_COLLISION_COUNT + 1 ) ) { // Still enough overhead. return ; } Object [ ] oldTable = table ; // Grow the table so it increases by 1 / GROWTH_DENOMINATOR. int newSize = currentSize + currentSize / GROWTH_DENOMINATOR ; table = new Object [ newSize ] ; count = 0 ; for ( Object element : oldTable ) { if ( element != null ) { intern ( element ) ; } } }
Doubles the table size .
146
6
30,412
private Statement handleBasicTranslation ( List < SoyPrintDirective > escapingDirectives , Expression soyMsgParts ) { // optimize for simple constant translations (very common) // this becomes: renderContext.getSoyMessge(<id>).getParts().get(0).getRawText() SoyExpression text = SoyExpression . forString ( soyMsgParts . invoke ( MethodRef . LIST_GET , constant ( 0 ) ) . checkedCast ( SoyMsgRawTextPart . class ) . invoke ( MethodRef . SOY_MSG_RAW_TEXT_PART_GET_RAW_TEXT ) ) ; // Note: there is no point in trying to stream here, since we are starting with a constant // string. for ( SoyPrintDirective directive : escapingDirectives ) { text = parameterLookup . getRenderContext ( ) . applyPrintDirective ( directive , text ) ; } return appendableExpression . appendString ( text . coerceToString ( ) ) . toStatement ( ) ; }
Handles a translation consisting of a single raw text node .
213
12
30,413
private Statement handleTranslationWithPlaceholders ( MsgNode msg , ImmutableList < SoyPrintDirective > escapingDirectives , Expression soyMsgParts , Expression locale , MsgPartsAndIds partsAndId ) { // We need to render placeholders into a buffer and then pack them into a map to pass to // Runtime.renderSoyMsgWithPlaceholders. Map < String , Function < Expression , Statement > > placeholderNameToPutStatement = new LinkedHashMap <> ( ) ; putPlaceholdersIntoMap ( msg , partsAndId . parts , placeholderNameToPutStatement ) ; // sanity check checkState ( ! placeholderNameToPutStatement . isEmpty ( ) ) ; ConstructorRef cstruct = msg . isPlrselMsg ( ) ? ConstructorRef . PLRSEL_MSG_RENDERER : ConstructorRef . MSG_RENDERER ; Statement initRendererStatement = variables . getCurrentRenderee ( ) . putInstanceField ( thisVar , cstruct . construct ( constant ( partsAndId . id ) , soyMsgParts , locale , constant ( placeholderNameToPutStatement . size ( ) ) ) ) ; List < Statement > initializationStatements = new ArrayList <> ( ) ; initializationStatements . add ( initRendererStatement ) ; for ( Function < Expression , Statement > fn : placeholderNameToPutStatement . values ( ) ) { initializationStatements . add ( fn . apply ( variables . getCurrentRenderee ( ) . accessor ( thisVar ) ) ) ; } Statement initMsgRenderer = Statement . concat ( initializationStatements ) ; Statement render ; if ( areAllPrintDirectivesStreamable ( escapingDirectives ) ) { AppendableAndOptions wrappedAppendable = applyStreamingEscapingDirectives ( escapingDirectives , appendableExpression , parameterLookup . getPluginContext ( ) , variables ) ; FieldRef currentAppendableField = variables . getCurrentAppendable ( ) ; Statement initAppendable = currentAppendableField . putInstanceField ( thisVar , wrappedAppendable . appendable ( ) ) ; Expression appendableExpression = currentAppendableField . accessor ( thisVar ) ; Statement clearAppendable = currentAppendableField . putInstanceField ( thisVar , constantNull ( LOGGING_ADVISING_APPENDABLE_TYPE ) ) ; if ( wrappedAppendable . closeable ( ) ) { clearAppendable = Statement . concat ( appendableExpression . checkedCast ( BytecodeUtils . CLOSEABLE_TYPE ) . invokeVoid ( MethodRef . CLOSEABLE_CLOSE ) , clearAppendable ) ; } render = Statement . concat ( initAppendable , detachState . detachForRender ( variables . getCurrentRenderee ( ) . accessor ( thisVar ) . invoke ( MethodRef . SOY_VALUE_PROVIDER_RENDER_AND_RESOLVE , appendableExpression , // set the isLast field to true since we know this will only be rendered // once. /* isLast=*/ constant ( true ) ) ) , clearAppendable ) ; } else { Label start = new Label ( ) ; SoyExpression value = SoyExpression . forSoyValue ( StringType . getInstance ( ) , detachState . createExpressionDetacher ( start ) . resolveSoyValueProvider ( variables . getCurrentRenderee ( ) . accessor ( thisVar ) ) . checkedCast ( SOY_STRING_TYPE ) ) ; for ( SoyPrintDirective directive : escapingDirectives ) { value = parameterLookup . getRenderContext ( ) . applyPrintDirective ( directive , value ) ; } render = appendableExpression . appendString ( value . unboxAsString ( ) ) . toStatement ( ) . labelStart ( start ) ; } return Statement . concat ( initMsgRenderer , render , // clear the field variables . getCurrentRenderee ( ) . putInstanceField ( thisVar , BytecodeUtils . constantNull ( ConstructorRef . MSG_RENDERER . instanceClass ( ) . type ( ) ) ) ) ; }
Handles a complex message with placeholders .
890
9
30,414
private Function < Expression , Statement > addNodeToPlaceholderMap ( String mapKey , StandaloneNode node ) { return putToMapFunction ( mapKey , placeholderCompiler . compileToSoyValueProvider ( mapKey , node , /* prefix= */ ExtraCodeCompiler . NO_OP , /* suffix= */ ExtraCodeCompiler . NO_OP ) ) ; }
Returns a statement that adds the content rendered by the call to the map .
78
15
30,415
public static JsExpr concatJsExprs ( List < ? extends JsExpr > jsExprs ) { if ( jsExprs . isEmpty ( ) ) { return EMPTY_STRING ; } if ( jsExprs . size ( ) == 1 ) { return jsExprs . get ( 0 ) ; } int plusOpPrec = Operator . PLUS . getPrecedence ( ) ; StringBuilder resultSb = new StringBuilder ( ) ; boolean isFirst = true ; for ( JsExpr jsExpr : jsExprs ) { // The first operand needs protection only if it's strictly lower precedence. The non-first // operands need protection when they're lower or equal precedence. (This is true for all // left-associative operators.) boolean needsProtection = isFirst ? jsExpr . getPrecedence ( ) < plusOpPrec : jsExpr . getPrecedence ( ) <= plusOpPrec ; if ( isFirst ) { isFirst = false ; } else { resultSb . append ( " + " ) ; } if ( needsProtection ) { resultSb . append ( ' ' ) . append ( jsExpr . getText ( ) ) . append ( ' ' ) ; } else { resultSb . append ( jsExpr . getText ( ) ) ; } } return new JsExpr ( resultSb . toString ( ) , plusOpPrec ) ; }
Builds one JS expression that computes the concatenation of the given JS expressions . The + operator is used for concatenation . Operands will be protected with an extra pair of parentheses if and only if needed .
317
45
30,416
@ VisibleForTesting static JsExpr wrapWithFunction ( String functionExprText , JsExpr jsExpr ) { Preconditions . checkNotNull ( functionExprText ) ; return new JsExpr ( functionExprText + "(" + jsExpr . getText ( ) + ")" , Integer . MAX_VALUE ) ; }
Wraps an expression in a function call .
78
9
30,417
@ SuppressWarnings ( "unchecked" ) private int mergeRange ( ParentSoyNode < ? > parent , int start , int lastNonEmptyRawTextNode , int end ) { checkArgument ( start < end ) ; if ( start == - 1 || end == start + 1 ) { return end ; } // general case, there are N rawtextnodes to merge where n > 1 // merge all the nodes together, then drop all the raw text nodes from the end RawTextNode newNode = RawTextNode . concat ( ( List < RawTextNode > ) parent . getChildren ( ) . subList ( start , lastNonEmptyRawTextNode + 1 ) ) ; ( ( ParentSoyNode ) parent ) . replaceChild ( start , newNode ) ; for ( int i = end - 1 ; i > start ; i -- ) { parent . removeChild ( i ) ; } return start + 1 ; }
RawTextNodes and if we can remove a RawTextNode we can also add one .
197
19
30,418
public void writeEntry ( String path , ByteSource contents ) throws IOException { stream . putNextEntry ( new ZipEntry ( path ) ) ; contents . copyTo ( stream ) ; stream . closeEntry ( ) ; }
Writes a single entry to the jar .
46
9
30,419
private static Manifest standardSoyJarManifest ( ) { Manifest mf = new Manifest ( ) ; mf . getMainAttributes ( ) . put ( Attributes . Name . MANIFEST_VERSION , "1.0" ) ; mf . getMainAttributes ( ) . put ( new Attributes . Name ( "Created-By" ) , "soy" ) ; return mf ; }
Returns a simple jar manifest .
83
6
30,420
private void addTypeSubstitutions ( Map < Wrapper < ExprNode > , SoyType > substitutionsToAdd ) { for ( Map . Entry < Wrapper < ExprNode > , SoyType > entry : substitutionsToAdd . entrySet ( ) ) { ExprNode expr = entry . getKey ( ) . get ( ) ; // Get the existing type SoyType previousType = expr . getType ( ) ; for ( TypeSubstitution subst = substitutions ; subst != null ; subst = subst . parent ) { if ( ExprEquivalence . get ( ) . equivalent ( subst . expression , expr ) ) { previousType = subst . type ; break ; } } // If the new type is different than the current type, then add a new type substitution. if ( ! entry . getValue ( ) . equals ( previousType ) ) { substitutions = new TypeSubstitution ( substitutions , expr , entry . getValue ( ) ) ; } } }
active substitutions .
207
4
30,421
private SoyType getElementType ( SoyType collectionType , ForNonemptyNode node ) { Preconditions . checkNotNull ( collectionType ) ; switch ( collectionType . getKind ( ) ) { case UNKNOWN : // If we don't know anything about the base type, then make no assumptions // about the field type. return UnknownType . getInstance ( ) ; case LIST : if ( collectionType == ListType . EMPTY_LIST ) { errorReporter . report ( node . getParent ( ) . getSourceLocation ( ) , EMPTY_LIST_FOREACH ) ; return ErrorType . getInstance ( ) ; } return ( ( ListType ) collectionType ) . getElementType ( ) ; case UNION : { // If it's a union, then do the field type calculation for each member of // the union and combine the result. UnionType unionType = ( UnionType ) collectionType ; List < SoyType > fieldTypes = new ArrayList <> ( unionType . getMembers ( ) . size ( ) ) ; for ( SoyType unionMember : unionType . getMembers ( ) ) { SoyType elementType = getElementType ( unionMember , node ) ; if ( elementType . getKind ( ) == SoyType . Kind . ERROR ) { return ErrorType . getInstance ( ) ; } fieldTypes . add ( elementType ) ; } return SoyTypes . computeLowestCommonType ( typeRegistry , fieldTypes ) ; } default : errorReporter . report ( node . getParent ( ) . getSourceLocation ( ) , BAD_FOREACH_TYPE , node . getExpr ( ) . toSourceString ( ) , node . getExpr ( ) . getType ( ) ) ; // Report the outermost union type in the error. return ErrorType . getInstance ( ) ; } }
Given a collection type compute the element type .
383
9
30,422
public SoySauceBuilder withPluginInstances ( Map < String , Supplier < Object > > pluginInstances ) { this . userPluginInstances = ImmutableMap . copyOf ( pluginInstances ) ; return this ; }
Sets the plugin instance factories to be used when constructing the SoySauce .
49
17
30,423
SoySauceBuilder withFunctions ( Map < String , ? extends SoyFunction > userFunctions ) { this . userFunctions = ImmutableMap . copyOf ( userFunctions ) ; return this ; }
Sets the user functions .
46
6
30,424
SoySauceBuilder withDirectives ( Map < String , ? extends SoyPrintDirective > userDirectives ) { this . userDirectives = ImmutableMap . copyOf ( userDirectives ) ; return this ; }
Sets user directives . Not exposed externally because internal directives should be enough and additional functionality can be built as SoySourceFunctions .
48
26
30,425
public SoySauce build ( ) { if ( scopedData == null ) { scopedData = new SoySimpleScope ( ) ; } if ( loader == null ) { loader = SoySauceBuilder . class . getClassLoader ( ) ; } return new SoySauceImpl ( new CompiledTemplates ( readDelTemplatesFromMetaInf ( loader ) , loader ) , scopedData . enterable ( ) , userFunctions , // We don't need internal functions because they only matter at compile time ImmutableMap . < String , SoyPrintDirective > builder ( ) // but internal directives are still required at render time. // in order to handle escaping logging function invocations. . putAll ( InternalPlugins . internalDirectiveMap ( scopedData ) ) . putAll ( userDirectives ) . build ( ) , userPluginInstances ) ; }
Creates a SoySauce .
184
8
30,426
private static ImmutableSet < String > readDelTemplatesFromMetaInf ( ClassLoader loader ) { try { ImmutableSet . Builder < String > builder = ImmutableSet . builder ( ) ; Enumeration < URL > resources = loader . getResources ( Names . META_INF_DELTEMPLATE_PATH ) ; while ( resources . hasMoreElements ( ) ) { URL url = resources . nextElement ( ) ; try ( InputStream in = url . openStream ( ) ) { BufferedReader reader = new BufferedReader ( new InputStreamReader ( in , UTF_8 ) ) ; for ( String line = reader . readLine ( ) ; line != null ; line = reader . readLine ( ) ) { builder . add ( line ) ; } } } return builder . build ( ) ; } catch ( IOException iox ) { throw new RuntimeException ( "Unable to read deltemplate listing" , iox ) ; } }
Walks all resources with the META_INF_DELTEMPLATE_PATH and collects the deltemplates .
204
27
30,427
public boolean exec ( TemplateNode template ) { boolean hasOptional = false ; for ( TemplateParam param : template . getParams ( ) ) { if ( param . isRequired ( ) ) { // If there exists a required param, then data should already be defined (no need to // ensure). return false ; } else { hasOptional = true ; } } if ( hasOptional ) { // If all params are optional (and there is at least one), then we need to ensure data is // defined. This is because the only legal way to have an optional param is if you reference // it somewhere in the template, so there is no need to check. return true ; } // If we get here then the template has no declared params and we are observing a v1 compatible // template. Search for things that could be data references: // * possibleParams // * data=All calls // others? return new AbstractNodeVisitor < Node , Boolean > ( ) { boolean shouldEnsureDataIsDefined ; @ Override public Boolean exec ( Node node ) { visit ( node ) ; return shouldEnsureDataIsDefined ; } @ Override public void visit ( Node node ) { if ( node instanceof VarRefNode ) { VarRefNode varRefNode = ( VarRefNode ) node ; VarDefn var = varRefNode . getDefnDecl ( ) ; // Don't include injected params in this analysis if ( varRefNode . isPossibleHeaderVar ( ) && var . kind ( ) != VarDefn . Kind . STATE && ( var . kind ( ) != VarDefn . Kind . PARAM // a soydoc param -> not ij || ! ( ( TemplateParam ) var ) . isInjected ( ) ) ) { // an {@param but not {@inject shouldEnsureDataIsDefined = true ; return ; } } if ( node instanceof CallNode ) { if ( ( ( CallNode ) node ) . isPassingAllData ( ) ) { shouldEnsureDataIsDefined = true ; return ; } } if ( node instanceof ParentNode ) { for ( Node child : ( ( ParentNode < ? > ) node ) . getChildren ( ) ) { visit ( child ) ; if ( shouldEnsureDataIsDefined ) { return ; } } } if ( node instanceof ExprHolderNode ) { for ( ExprRootNode expr : ( ( ExprHolderNode ) node ) . getExprList ( ) ) { visit ( expr ) ; if ( shouldEnsureDataIsDefined ) { return ; } } } } } . exec ( template ) ; }
Runs this pass on the given template .
553
9
30,428
static void checkId ( String id ) { if ( ! ID . matcher ( id ) . matches ( ) ) { throw new IllegalArgumentException ( String . format ( "not a valid js identifier: %s" , id ) ) ; } }
Validates that the given string is a valid javascript identifier .
53
12
30,429
Iterable < ClassData > compile ( ) { List < ClassData > classes = new ArrayList <> ( ) ; // first generate the factory if ( templateNode . getVisibility ( ) != Visibility . PRIVATE ) { // Don't generate factory if the template is private. The factories are only // useful to instantiate templates for calls from java. Soy->Soy calls should invoke // constructors directly. new TemplateFactoryCompiler ( template , templateNode , innerClasses ) . compile ( ) ; } writer = SoyClassWriter . builder ( template . typeInfo ( ) ) . setAccess ( Opcodes . ACC_PUBLIC + Opcodes . ACC_SUPER + Opcodes . ACC_FINAL ) . implementing ( TEMPLATE_TYPE ) . sourceFileName ( templateNode . getSourceLocation ( ) . getFileName ( ) ) . build ( ) ; generateTemplateMetadata ( ) ; generateKindMethod ( ) ; stateField . defineField ( writer ) ; paramsField . defineField ( writer ) ; ijField . defineField ( writer ) ; for ( FieldRef field : paramFields . values ( ) ) { field . defineField ( writer ) ; } ImmutableMap < TemplateParam , SoyExpression > defaultParamInitializers = generateRenderMethod ( ) ; generateConstructor ( defaultParamInitializers ) ; innerClasses . registerAllInnerClasses ( writer ) ; writer . visitEnd ( ) ; classes . add ( writer . toClassData ( ) ) ; classes . addAll ( innerClasses . getInnerClassData ( ) ) ; writer = null ; return classes ; }
Returns the list of classes needed to implement this template .
343
11
30,430
private void generateConstructor ( ImmutableMap < TemplateParam , SoyExpression > defaultParamInitializers ) { final Label start = new Label ( ) ; final Label end = new Label ( ) ; final LocalVariable thisVar = createThisVar ( template . typeInfo ( ) , start , end ) ; final LocalVariable paramsVar = createLocal ( "params" , 1 , SOY_RECORD_TYPE , start , end ) ; final LocalVariable ijVar = createLocal ( "ij" , 2 , SOY_RECORD_TYPE , start , end ) ; final List < Statement > assignments = new ArrayList <> ( ) ; assignments . add ( paramsField . putInstanceField ( thisVar , paramsVar ) ) ; assignments . add ( ijField . putInstanceField ( thisVar , ijVar ) ) ; for ( TemplateParam param : templateNode . getAllParams ( ) ) { Expression paramProvider = getParam ( paramsVar , ijVar , param , defaultParamInitializers . get ( param ) ) ; assignments . add ( paramFields . get ( param . name ( ) ) . putInstanceField ( thisVar , paramProvider ) ) ; } Statement constructorBody = new Statement ( ) { @ Override protected void doGen ( CodeBuilder ga ) { ga . mark ( start ) ; // call super() thisVar . gen ( ga ) ; ga . invokeConstructor ( OBJECT . type ( ) , NULLARY_INIT ) ; for ( Statement assignment : assignments ) { assignment . gen ( ga ) ; } ga . visitInsn ( Opcodes . RETURN ) ; ga . visitLabel ( end ) ; thisVar . tableEntry ( ga ) ; paramsVar . tableEntry ( ga ) ; ijVar . tableEntry ( ga ) ; } } ; constructorBody . writeMethod ( Opcodes . ACC_PUBLIC , template . constructor ( ) . method ( ) , writer ) ; }
Generate a public constructor that assigns our final field and checks for missing required params .
406
17
30,431
static void checkTypes ( ImmutableList < Type > types , Iterable < ? extends Expression > exprs ) { int size = Iterables . size ( exprs ) ; checkArgument ( size == types . size ( ) , "Supplied the wrong number of parameters. Expected %s, got %s" , types . size ( ) , size ) ; // checkIsAssignableTo is an no-op if DEBUG is false if ( Flags . DEBUG ) { int i = 0 ; for ( Expression expr : exprs ) { expr . checkAssignableTo ( types . get ( i ) , "Parameter %s" , i ) ; i ++ ; } } }
Checks that the given expressions are compatible with the given types .
143
13
30,432
public Statement toStatement ( ) { return new Statement ( ) { @ Override protected void doGen ( CodeBuilder adapter ) { Expression . this . gen ( adapter ) ; switch ( resultType ( ) . getSize ( ) ) { case 0 : throw new AssertionError ( "void expressions are not allowed" ) ; case 1 : adapter . pop ( ) ; break ; case 2 : adapter . pop2 ( ) ; break ; default : throw new AssertionError ( ) ; } } } ; }
Convert this expression to a statement by executing it and throwing away the result .
106
16
30,433
public Expression checkedCast ( final Type target ) { checkArgument ( target . getSort ( ) == Type . OBJECT , "cast targets must be reference types. (%s)" , target . getClassName ( ) ) ; checkArgument ( resultType ( ) . getSort ( ) == Type . OBJECT , "you may only cast from reference types. (%s)" , resultType ( ) . getClassName ( ) ) ; if ( BytecodeUtils . isDefinitelyAssignableFrom ( target , resultType ( ) ) ) { return this ; } return new Expression ( target , features ( ) ) { @ Override protected void doGen ( CodeBuilder adapter ) { Expression . this . gen ( adapter ) ; // TODO(b/191662001) Remove this once we have fully switched the type // system over. Normally, we should just cast this result over, but in // the case of SoyString, there are temporarily two states (SanitizedContent == SoyString) // and (SanitizedContent != SoyString). This branch bails out to a runtime function that // effectively does the below but also optionally logs a warning. if ( resultType ( ) . equals ( BytecodeUtils . SOY_STRING_TYPE ) ) { MethodRef . RUNTIME_CHECK_SOY_STRING . invokeUnchecked ( adapter ) ; } else { adapter . checkCast ( resultType ( ) ) ; } } } ; }
Returns an expression that performs a checked cast from the current type to the target type .
303
17
30,434
public Expression labelStart ( final Label label ) { return new Expression ( resultType ( ) , features ) { @ Override protected void doGen ( CodeBuilder adapter ) { adapter . mark ( label ) ; Expression . this . gen ( adapter ) ; } } ; }
Returns a new expression identical to this one but with the given label applied at the start of the expression .
55
21
30,435
public void setParamsToRuntimeCheck ( Predicate < String > paramNames ) { checkState ( this . paramsToRuntimeTypeCheck == null ) ; this . paramsToRuntimeTypeCheck = checkNotNull ( paramNames ) ; }
Sets the names of the params that require runtime type checking against callee s types .
49
18
30,436
public static SanitizedContent cleanHtml ( SoyValue value , Collection < ? extends OptionalSafeTag > optionalSafeTags ) { value = normalizeNull ( value ) ; Dir valueDir = null ; if ( value instanceof SanitizedContent ) { SanitizedContent sanitizedContent = ( SanitizedContent ) value ; if ( sanitizedContent . getContentKind ( ) == SanitizedContent . ContentKind . HTML ) { return ( SanitizedContent ) value ; } valueDir = sanitizedContent . getContentDirection ( ) ; } return cleanHtml ( value . coerceToString ( ) , valueDir , optionalSafeTags ) ; }
Normalizes the input HTML while preserving safe tags and the known directionality .
134
15
30,437
public static SanitizedContent cleanHtml ( String value , Collection < ? extends OptionalSafeTag > optionalSafeTags ) { return cleanHtml ( value , null , optionalSafeTags ) ; }
Normalizes the input HTML while preserving safe tags . The content directionality is unknown .
40
17
30,438
public static SanitizedContent cleanHtml ( String value , Dir contentDir , Collection < ? extends OptionalSafeTag > optionalSafeTags ) { return UnsafeSanitizedContentOrdainer . ordainAsSafe ( stripHtmlTags ( value , TagWhitelist . FORMATTING . withOptionalSafeTags ( optionalSafeTags ) , true ) , ContentKind . HTML , contentDir ) ; }
Normalizes the input HTML of a given directionality while preserving safe tags .
81
15
30,439
public static String normalizeHtml ( SoyValue value ) { value = normalizeNull ( value ) ; return normalizeHtml ( value . coerceToString ( ) ) ; }
Normalizes HTML to HTML making sure quotes and other specials are entity encoded .
39
15
30,440
public static String normalizeHtmlNospace ( SoyValue value ) { value = normalizeNull ( value ) ; return normalizeHtmlNospace ( value . coerceToString ( ) ) ; }
Normalizes HTML to HTML making sure quotes spaces and other specials are entity encoded so that the result can be safely embedded in a valueless attribute .
43
29
30,441
public static String escapeHtmlAttribute ( SoyValue value ) { value = normalizeNull ( value ) ; if ( isSanitizedContentOfKind ( value , SanitizedContent . ContentKind . HTML ) ) { // |escapeHtmlAttribute should only be used on attribute values that cannot have tags. return stripHtmlTags ( value . coerceToString ( ) , null , true ) ; } return escapeHtmlAttribute ( value . coerceToString ( ) ) ; }
Converts the input to HTML by entity escaping stripping tags in sanitized content so the result can safely be embedded in an HTML attribute value .
100
28
30,442
public static String escapeHtmlAttributeNospace ( SoyValue value ) { value = normalizeNull ( value ) ; if ( isSanitizedContentOfKind ( value , SanitizedContent . ContentKind . HTML ) ) { // |escapeHtmlAttributeNospace should only be used on attribute values that cannot have tags. return stripHtmlTags ( value . coerceToString ( ) , null , false ) ; } return escapeHtmlAttributeNospace ( value . coerceToString ( ) ) ; }
Converts plain text to HTML by entity escaping stripping tags in sanitized content so the result can safely be embedded in an unquoted HTML attribute value .
106
31
30,443
public static String escapeUri ( SoyValue value ) { value = normalizeNull ( value ) ; return escapeUri ( value . coerceToString ( ) ) ; }
Converts the input to a piece of a URI by percent encoding the value as UTF - 8 bytes .
37
21
30,444
public static String filterNormalizeMediaUri ( String value ) { if ( EscapingConventions . FilterNormalizeMediaUri . INSTANCE . getValueFilter ( ) . matcher ( value ) . find ( ) ) { return EscapingConventions . FilterNormalizeMediaUri . INSTANCE . escape ( value ) ; } logger . log ( Level . WARNING , "|filterNormalizeMediaUri received bad value ''{0}''" , value ) ; return EscapingConventions . FilterNormalizeMediaUri . INSTANCE . getInnocuousOutput ( ) ; }
Checks that a URI is safe to be an image source .
125
13
30,445
public static String filterTrustedResourceUri ( SoyValue value ) { value = normalizeNull ( value ) ; if ( isSanitizedContentOfKind ( value , SanitizedContent . ContentKind . TRUSTED_RESOURCE_URI ) ) { return value . coerceToString ( ) ; } logger . log ( Level . WARNING , "|filterTrustedResourceUri received bad value ''{0}''" , value ) ; return "about:invalid#" + EscapingConventions . INNOCUOUS_OUTPUT ; }
Makes sure the given input is an instance of either trustedResourceUrl or trustedString .
118
18
30,446
public static SanitizedContent filterImageDataUri ( SoyValue value ) { value = normalizeNull ( value ) ; return filterImageDataUri ( value . coerceToString ( ) ) ; }
Makes sure that the given input is a data URI corresponding to an image .
43
16
30,447
public static SanitizedContent filterSipUri ( SoyValue value ) { value = normalizeNull ( value ) ; return filterSipUri ( value . coerceToString ( ) ) ; }
Makes sure that the given input is a sip URI .
43
12
30,448
public static SanitizedContent filterTelUri ( SoyValue value ) { value = normalizeNull ( value ) ; return filterTelUri ( value . coerceToString ( ) ) ; }
Makes sure that the given input is a tel URI .
41
12
30,449
public static String filterHtmlAttributes ( SoyValue value ) { value = normalizeNull ( value ) ; if ( isSanitizedContentOfKind ( value , SanitizedContent . ContentKind . ATTRIBUTES ) ) { // We're guaranteed to be in a case where key=value pairs are expected. However, if it would // cause issues to directly abut this with more attributes, add a space. For example: // {$a}{$b} where $a is foo=bar and $b is boo=baz requires a space in between to be parsed // correctly, but not in the case where $a is foo="bar". // TODO: We should be able to get rid of this if the compiler can guarantee spaces between // adjacent print statements in attribute context at compile time. String content = value . coerceToString ( ) ; if ( content . length ( ) > 0 ) { if ( shouldAppendSpace ( content . charAt ( content . length ( ) - 1 ) ) ) { content += ' ' ; } } return content ; } return filterHtmlAttributes ( value . coerceToString ( ) ) ; }
Checks that the input is a valid HTML attribute name with normal keyword or textual content or known safe attribute content .
241
23
30,450
public static String filterHtmlAttributes ( String value ) { if ( EscapingConventions . FilterHtmlAttributes . INSTANCE . getValueFilter ( ) . matcher ( value ) . find ( ) ) { return value ; } logger . log ( Level . WARNING , "|filterHtmlAttributes received bad value ''{0}''" , value ) ; return EscapingConventions . FilterHtmlAttributes . INSTANCE . getInnocuousOutput ( ) ; }
Checks that the input is a valid HTML attribute name with normal keyword or textual content .
99
18
30,451
private static boolean isSanitizedContentOfKind ( SoyValue value , SanitizedContent . ContentKind kind ) { return value instanceof SanitizedContent && kind == ( ( SanitizedContent ) value ) . getContentKind ( ) ; }
True iff the given value is sanitized content of the given kind .
49
15
30,452
private static String embedCssIntoHtmlSlow ( String css , int nextReplacement , boolean searchForEndCData , boolean searchForEndTag ) { // use an array instead of a stringbuilder so we can take advantage of the bulk copying // routine (String.getChars). For some reason StringBuilder doesn't do this. char [ ] buf = new char [ css . length ( ) + 16 ] ; int endOfPreviousReplacement = 0 ; int bufIndex = 0 ; do { int charsToCopy = nextReplacement - endOfPreviousReplacement ; buf = Chars . ensureCapacity ( buf , bufIndex + charsToCopy + 4 , 16 ) ; css . getChars ( endOfPreviousReplacement , nextReplacement , buf , bufIndex ) ; bufIndex += charsToCopy ; char c = css . charAt ( nextReplacement ) ; if ( c == ' ' ) { buf [ bufIndex ++ ] = ' ' ; buf [ bufIndex ++ ] = ' ' ; buf [ bufIndex ++ ] = ' ' ; buf [ bufIndex ++ ] = ' ' ; endOfPreviousReplacement = nextReplacement + 3 ; } else if ( c == ' ' ) { buf [ bufIndex ++ ] = ' ' ; buf [ bufIndex ++ ] = ' ' ; buf [ bufIndex ++ ] = ' ' ; endOfPreviousReplacement = nextReplacement + 2 ; } else { throw new AssertionError ( ) ; } nextReplacement = - 1 ; if ( searchForEndTag ) { int indexOfEndTag = css . indexOf ( "</" , endOfPreviousReplacement ) ; if ( indexOfEndTag == - 1 ) { searchForEndTag = false ; } else { nextReplacement = indexOfEndTag ; } } if ( searchForEndCData ) { int indexOfEndCData = css . indexOf ( "]]>" , endOfPreviousReplacement ) ; if ( indexOfEndCData == - 1 ) { searchForEndCData = false ; } else { nextReplacement = nextReplacement == - 1 ? indexOfEndCData : Math . min ( nextReplacement , indexOfEndCData ) ; } } } while ( nextReplacement != - 1 ) ; // copy tail int charsToCopy = css . length ( ) - endOfPreviousReplacement ; buf = Chars . ensureCapacity ( buf , bufIndex + charsToCopy , 16 ) ; css . getChars ( endOfPreviousReplacement , css . length ( ) , buf , bufIndex ) ; bufIndex += charsToCopy ; return new String ( buf , 0 , bufIndex ) ; }
Called when we know we need to make a replacement .
573
12
30,453
public ImmutableList < SoyMsgPart > getMsgParts ( long msgId ) { SoyMsg msg = getMsg ( msgId ) ; return msg == null ? ImmutableList . of ( ) : msg . getParts ( ) ; }
Returns the message parts or an empty array if there is no such message .
50
15
30,454
public static PyExpr concatPyExprs ( List < ? extends PyExpr > pyExprs ) { if ( pyExprs . isEmpty ( ) ) { return EMPTY_STRING ; } if ( pyExprs . size ( ) == 1 ) { // If there's only one element, simply return the expression as a String. return pyExprs . get ( 0 ) . toPyString ( ) ; } StringBuilder resultSb = new StringBuilder ( ) ; // Use Python's list joining mechanism to speed up concatenation. resultSb . append ( "[" ) ; boolean isFirst = true ; for ( PyExpr pyExpr : pyExprs ) { if ( isFirst ) { isFirst = false ; } else { resultSb . append ( ' ' ) ; } resultSb . append ( pyExpr . toPyString ( ) . getText ( ) ) ; } resultSb . append ( "]" ) ; return new PyListExpr ( resultSb . toString ( ) , Integer . MAX_VALUE ) ; }
Builds one Python expression that computes the concatenation of the given Python expressions .
234
18
30,455
public static PyExpr maybeProtect ( PyExpr expr , int minSafePrecedence ) { // all python operators are left associative, so if this has equivalent precedence we don't need // to wrap if ( expr . getPrecedence ( ) >= minSafePrecedence ) { return expr ; } else { return new PyExpr ( "(" + expr . getText ( ) + ")" , Integer . MAX_VALUE ) ; } }
Wraps an expression with parenthesis if it s not above the minimum safe precedence .
95
17
30,456
public static PyExpr convertMapToOrderedDict ( Map < PyExpr , PyExpr > dict ) { List < String > values = new ArrayList <> ( ) ; for ( Map . Entry < PyExpr , PyExpr > entry : dict . entrySet ( ) ) { values . add ( "(" + entry . getKey ( ) . getText ( ) + ", " + entry . getValue ( ) . getText ( ) + ")" ) ; } Joiner joiner = Joiner . on ( ", " ) ; return new PyExpr ( "collections.OrderedDict([" + joiner . join ( values ) + "])" , Integer . MAX_VALUE ) ; }
Convert a java Map to valid PyExpr as dict .
154
13
30,457
public static String genExprWithNewToken ( Operator op , List < ? extends TargetExpr > operandExprs , String newToken ) { int opPrec = op . getPrecedence ( ) ; boolean isLeftAssociative = op . getAssociativity ( ) == Associativity . LEFT ; StringBuilder exprSb = new StringBuilder ( ) ; // Iterate through the operator's syntax elements. List < SyntaxElement > syntax = op . getSyntax ( ) ; for ( int i = 0 , n = syntax . size ( ) ; i < n ; i ++ ) { SyntaxElement syntaxEl = syntax . get ( i ) ; if ( syntaxEl instanceof Operand ) { // Retrieve the operand's subexpression. int operandIndex = ( ( Operand ) syntaxEl ) . getIndex ( ) ; TargetExpr operandExpr = operandExprs . get ( operandIndex ) ; // If left (right) associative, first (last) operand doesn't need protection if it's an // operator of equal precedence to this one. boolean needsProtection ; if ( i == ( isLeftAssociative ? 0 : n - 1 ) ) { needsProtection = operandExpr . getPrecedence ( ) < opPrec ; } else { needsProtection = operandExpr . getPrecedence ( ) <= opPrec ; } // Append the operand's subexpression to the expression we're building (if necessary, // protected using parentheses). String subexpr = needsProtection ? "(" + operandExpr . getText ( ) + ")" : operandExpr . getText ( ) ; exprSb . append ( subexpr ) ; } else if ( syntaxEl instanceof Token ) { // If a newToken is supplied, then use it, else use the token defined by Soy syntax. if ( newToken != null ) { exprSb . append ( newToken ) ; } else { exprSb . append ( ( ( Token ) syntaxEl ) . getValue ( ) ) ; } } else if ( syntaxEl instanceof Spacer ) { // Spacer is just one space. exprSb . append ( ' ' ) ; } else { throw new AssertionError ( ) ; } } return exprSb . toString ( ) ; }
Generates an expression for the given operator and operands assuming that the expression for the operator uses the same syntax format as the Soy operator with the exception that the of a different token . Associativity spacing and precedence are maintained from the original operator .
499
49
30,458
private static StaticAnalysisResult isListExpressionEmpty ( ForNode node ) { Optional < RangeArgs > rangeArgs = RangeArgs . createFromNode ( node ) ; if ( rangeArgs . isPresent ( ) ) { return isRangeExpressionEmpty ( rangeArgs . get ( ) ) ; } ExprNode expr = node . getExpr ( ) . getRoot ( ) ; if ( expr instanceof ListLiteralNode ) { return ( ( ListLiteralNode ) expr ) . numChildren ( ) > 0 ? StaticAnalysisResult . FALSE : StaticAnalysisResult . TRUE ; } return StaticAnalysisResult . UNKNOWN ; }
consider moving this to SoyTreeUtils or some similar place .
132
13
30,459
public SoyMsgBundle createFromFile ( File inputFile ) throws IOException { // TODO: This is for backwards-compatibility. Figure out how to get rid of this. // We special-case English locales because they often don't have translated files and falling // back to the Soy source should be fine. if ( ! inputFile . exists ( ) && FIRST_WORD_IS_EN_PATTERN . matcher ( inputFile . getName ( ) ) . matches ( ) ) { return SoyMsgBundle . EMPTY ; } try { // reading the file as a byte array and then invoking the string constructor is the fastest // way to read a full file as a string. it avoids copies incurred by CharSource and picks a // faster path for charset decoding. String inputFileContent = Files . asCharSource ( inputFile , UTF_8 ) . read ( ) ; return msgPlugin . parseTranslatedMsgsFile ( inputFileContent ) ; } catch ( SoyMsgException sme ) { sme . setFileOrResourceName ( inputFile . toString ( ) ) ; throw sme ; } }
Reads a translated messages file and creates a SoyMsgBundle .
237
14
30,460
public SoyMsgBundle createFromResource ( URL inputResource ) throws IOException { try { String inputFileContent = Resources . asCharSource ( inputResource , UTF_8 ) . read ( ) ; return msgPlugin . parseTranslatedMsgsFile ( inputFileContent ) ; } catch ( SoyMsgException sme ) { sme . setFileOrResourceName ( inputResource . toString ( ) ) ; throw sme ; } }
Reads a translated messages resource and creates a SoyMsgBundle .
92
14
30,461
@ Nullable public HtmlCloseTagNode getCloseTagNode ( ) { if ( numChildren ( ) > 1 ) { return ( HtmlCloseTagNode ) getNodeAsHtmlTagNode ( getChild ( numChildren ( ) - 1 ) , /*openTag=*/ false ) ; } return null ; }
Returns the close tag node if it exists .
66
9
30,462
public static Locale parseLocale ( String localeString ) { if ( localeString == null ) { return Locale . US ; } String [ ] groups = localeString . split ( "[-_]" ) ; switch ( groups . length ) { case 1 : return new Locale ( groups [ 0 ] ) ; case 2 : return new Locale ( groups [ 0 ] , Ascii . toUpperCase ( groups [ 1 ] ) ) ; case 3 : return new Locale ( groups [ 0 ] , Ascii . toUpperCase ( groups [ 1 ] ) , groups [ 2 ] ) ; default : throw new IllegalArgumentException ( "Malformed localeString: " + localeString ) ; } }
Given a string representing a Locale returns the Locale object for that string .
151
16
30,463
public < T > void updateRefs ( T oldObject , T newObject ) { checkNotNull ( oldObject ) ; checkNotNull ( newObject ) ; checkArgument ( ! ( newObject instanceof Listener ) ) ; Object previousMapping = mappings . put ( oldObject , newObject ) ; if ( previousMapping != null ) { if ( previousMapping instanceof Listener ) { @ SuppressWarnings ( "unchecked" ) // Listener<T> can only be registered with a T Listener < T > listener = ( Listener < T > ) previousMapping ; listener . newVersion ( newObject ) ; } else { throw new IllegalStateException ( "found multiple remappings for " + oldObject ) ; } } }
Registers that the old object has been remapped to the new object .
162
15
30,464
public void checkAllListenersFired ( ) { for ( Map . Entry < Object , Object > entry : mappings . entrySet ( ) ) { if ( entry . getValue ( ) instanceof Listener ) { throw new IllegalStateException ( "Listener for " + entry . getKey ( ) + " never fired: " + entry . getValue ( ) ) ; } } }
Asserts that there are no pending listeners .
81
10
30,465
public static String unescapeHtml ( String s ) { int amp = s . indexOf ( ' ' ) ; if ( amp < 0 ) { // Fast path. return s ; } int n = s . length ( ) ; StringBuilder sb = new StringBuilder ( n ) ; int pos = 0 ; do { // All numeric entities and all named entities can be represented in less than 12 chars, so // avoid any O(n**2) problem on "&&&&&&&&&" by not looking for ; more than 12 chars out. int end = - 1 ; int entityLimit = Math . min ( n , amp + 12 ) ; for ( int i = amp + 1 ; i < entityLimit ; ++ i ) { if ( s . charAt ( i ) == ' ' ) { end = i + 1 ; break ; } } int cp = - 1 ; if ( end == - 1 ) { cp = - 1 ; } else { if ( s . charAt ( amp + 1 ) == ' ' ) { // Decode a numeric entity char ch = s . charAt ( amp + 2 ) ; try { if ( ch == ' ' || ch == ' ' ) { // hex // & # x A B C D ; // ^ ^ ^ ^ ^ // amp + 0 1 2 3 end - 1 cp = Integer . parseInt ( s . substring ( amp + 3 , end - 1 ) , 16 ) ; } else { // decimal // & # 1 6 0 ; // ^ ^ ^ ^ // amp + 0 1 2 end - 1 cp = Integer . parseInt ( s . substring ( amp + 2 , end - 1 ) , 10 ) ; } } catch ( NumberFormatException ex ) { cp = - 1 ; // Malformed numeric entity } } else { // & q u o t ; // ^ ^ // amp end Integer cpI = HTML_ENTITY_TO_CODEPOINT . get ( s . substring ( amp , end ) ) ; cp = cpI != null ? cpI . intValue ( ) : - 1 ; } } if ( cp == - 1 ) { // Don't decode end = amp + 1 ; } else { sb . append ( s , pos , amp ) ; sb . appendCodePoint ( cp ) ; pos = end ; } amp = s . indexOf ( ' ' , end ) ; } while ( amp >= 0 ) ; return sb . append ( s , pos , n ) . toString ( ) ; }
Replace all the occurrences of HTML entities with the appropriate code - points .
525
15
30,466
private List < String > genPySrc ( SoyFileSetNode soyTree , SoyPySrcOptions pySrcOptions , ImmutableMap < String , String > currentManifest , ErrorReporter errorReporter ) { BidiGlobalDir bidiGlobalDir = SoyBidiUtils . decodeBidiGlobalDirFromPyOptions ( pySrcOptions . getBidiIsRtlFn ( ) ) ; try ( SoyScopedData . InScope inScope = apiCallScope . enter ( /* msgBundle= */ null , bidiGlobalDir ) ) { return createVisitor ( pySrcOptions , inScope . getBidiGlobalDir ( ) , errorReporter , currentManifest ) . gen ( soyTree , errorReporter ) ; } }
Generates Python source code given a Soy parse tree and an options object .
163
15
30,467
public void genPyFiles ( SoyFileSetNode soyTree , SoyPySrcOptions pySrcOptions , String outputPathFormat , ErrorReporter errorReporter ) throws IOException { ImmutableList < SoyFileNode > srcsToCompile = ImmutableList . copyOf ( soyTree . getChildren ( ) ) ; // Determine the output paths. List < String > soyNamespaces = getSoyNamespaces ( soyTree ) ; Multimap < String , Integer > outputs = MainEntryPointUtils . mapOutputsToSrcs ( null , outputPathFormat , srcsToCompile ) ; // Generate the manifest and add it to the current manifest. ImmutableMap < String , String > manifest = generateManifest ( soyNamespaces , outputs ) ; // Generate the Python source. List < String > pyFileContents = genPySrc ( soyTree , pySrcOptions , manifest , errorReporter ) ; if ( srcsToCompile . size ( ) != pyFileContents . size ( ) ) { throw new AssertionError ( String . format ( "Expected to generate %d code chunk(s), got %d" , srcsToCompile . size ( ) , pyFileContents . size ( ) ) ) ; } // Write out the Python outputs. for ( String outputFilePath : outputs . keySet ( ) ) { try ( Writer out = Files . newWriter ( new File ( outputFilePath ) , StandardCharsets . UTF_8 ) ) { for ( int inputFileIndex : outputs . get ( outputFilePath ) ) { out . write ( pyFileContents . get ( inputFileIndex ) ) ; } } } // Write out the manifest file. if ( pySrcOptions . namespaceManifestFile ( ) != null ) { try ( Writer out = Files . newWriter ( new File ( pySrcOptions . namespaceManifestFile ( ) ) , StandardCharsets . UTF_8 ) ) { Properties prop = new Properties ( ) ; for ( String namespace : manifest . keySet ( ) ) { prop . put ( namespace , manifest . get ( namespace ) ) ; } prop . store ( out , null ) ; } } }
Generates Python source files given a Soy parse tree an options object and information on where to put the output files .
466
23
30,468
private static ImmutableMap < String , String > generateManifest ( List < String > soyNamespaces , Multimap < String , Integer > outputs ) { ImmutableMap . Builder < String , String > manifest = new ImmutableMap . Builder <> ( ) ; for ( String outputFilePath : outputs . keySet ( ) ) { for ( int inputFileIndex : outputs . get ( outputFilePath ) ) { String pythonPath = outputFilePath . replace ( ".py" , "" ) . replace ( ' ' , ' ' ) ; manifest . put ( soyNamespaces . get ( inputFileIndex ) , pythonPath ) ; } } return manifest . build ( ) ; }
Generate the manifest file by finding the output file paths and converting them into a Python import format .
143
20
30,469
public void check ( SoyFileNode file , final ErrorReporter errorReporter ) { // first filter to only the rules that need to be checked for this file. final List < Rule < ? > > rulesForFile = new ArrayList <> ( rules . size ( ) ) ; String filePath = file . getFilePath ( ) ; for ( RuleWithWhitelists rule : rules ) { if ( rule . shouldCheckConformanceFor ( filePath ) ) { rulesForFile . add ( rule . getRule ( ) ) ; } } if ( rulesForFile . isEmpty ( ) ) { return ; } SoyTreeUtils . visitAllNodes ( file , new NodeVisitor < Node , VisitDirective > ( ) { @ Override public VisitDirective exec ( Node node ) { for ( Rule < ? > rule : rulesForFile ) { rule . checkConformance ( node , errorReporter ) ; } // always visit all children return VisitDirective . CONTINUE ; } } ) ; }
Performs the overall check .
213
6
30,470
public static SoyType getTypeForContentKind ( SanitizedContentKind contentKind ) { switch ( contentKind ) { case ATTRIBUTES : return AttributesType . getInstance ( ) ; case CSS : return StyleType . getInstance ( ) ; case HTML : return HtmlType . getInstance ( ) ; case JS : return JsType . getInstance ( ) ; case URI : return UriType . getInstance ( ) ; case TRUSTED_RESOURCE_URI : return TrustedResourceUriType . getInstance ( ) ; case TEXT : return StringType . getInstance ( ) ; } throw new AssertionError ( contentKind ) ; }
Given a content kind return the corresponding soy type .
138
10
30,471
private static < T > T instantiateObject ( String flagName , String objectType , Class < T > clazz , PluginLoader loader , String instanceClassName ) { try { return loader . loadPlugin ( instanceClassName ) . asSubclass ( clazz ) . getConstructor ( ) . newInstance ( ) ; } catch ( ClassCastException cce ) { throw new CommandLineError ( String . format ( "%s \"%s\" is not a subclass of %s. Classes passed to %s should be %ss. " + "Did you pass it to the wrong flag?" , objectType , instanceClassName , clazz . getSimpleName ( ) , flagName , clazz . getSimpleName ( ) ) , cce ) ; } catch ( ReflectiveOperationException e ) { throw new CommandLineError ( String . format ( "Cannot instantiate %s \"%s\" registered with flag %s. Please make " + "sure that the %s exists and is on the compiler classpath and has a public " + "zero arguments constructor." , objectType , instanceClassName , flagName , objectType ) , e ) ; } catch ( ExceptionInInitializerError e ) { throw new CommandLineError ( String . format ( "Cannot instantiate %s \"%s\" registered with flag %s. An error was thrown while " + "loading the class. There is a bug in the implementation." , objectType , instanceClassName , flagName ) , e ) ; } catch ( SecurityException e ) { throw new CommandLineError ( String . format ( "Cannot instantiate %s \"%s\" registered with flag %s. A security manager is " + "preventing instantiation." , objectType , instanceClassName , flagName ) , e ) ; } }
Private helper for creating objects from flags .
379
8
30,472
public JsCodeBuilder addChunksToOutputVar ( List < ? extends Expression > codeChunks ) { if ( currOutputVarIsInited ) { Expression rhs = CodeChunkUtils . concatChunks ( codeChunks ) ; rhs . collectRequires ( requireCollector ) ; appendLine ( currOutputVar . plusEquals ( rhs ) . getCode ( ) ) ; } else { Expression rhs = CodeChunkUtils . concatChunksForceString ( codeChunks ) ; rhs . collectRequires ( requireCollector ) ; append ( VariableDeclaration . builder ( currOutputVar . singleExprOrName ( ) . getText ( ) ) . setRhs ( rhs ) . build ( ) ) ; setOutputVarInited ( ) ; } return this ; }
Appends one or more lines representing the concatenation of the values of the given code chunks saved to the current output variable .
176
26
30,473
private JsCodeBuilder changeIndentHelper ( int chg ) { int newIndentDepth = indent . length ( ) + chg * INDENT_SIZE ; Preconditions . checkState ( newIndentDepth >= 0 ) ; indent = Strings . repeat ( " " , newIndentDepth ) ; return this ; }
Helper for the various indent methods .
70
7
30,474
static SanitizedContent create ( String content , ContentKind kind ) { checkArgument ( kind != ContentKind . TEXT , "Use UnsanitizedString for SanitizedContent with a kind of TEXT" ) ; if ( Flags . stringIsNotSanitizedContent ( ) ) { return new SanitizedContent ( content , kind , kind . getDefaultDir ( ) ) ; } return SanitizedCompatString . create ( content , kind , kind . getDefaultDir ( ) ) ; }
Creates a SanitizedContent object with default direction .
99
11
30,475
public static StreamingEscaper create ( LoggingAdvisingAppendable delegate , CrossLanguageStringXform transform ) { if ( delegate instanceof StreamingEscaper ) { StreamingEscaper delegateAsStreamingEscaper = ( StreamingEscaper ) delegate ; if ( delegateAsStreamingEscaper . transform == transform ) { return delegateAsStreamingEscaper ; } } return new StreamingEscaper ( delegate , transform ) ; }
Creates a streaming escaper or returns the delegate if it is already escaping with the same settings .
87
20
30,476
public void onResolve ( ResolutionCallback callback ) { checkState ( this . resolveCallback == null , "callback has already been set." ) ; checkState ( this . value == null , "value is resolved." ) ; this . resolveCallback = checkNotNull ( callback ) ; }
Registers a callback that is invoked when this global is resolved to its actual value .
59
17
30,477
public static Statement assign ( Expression lhs , Expression rhs ) { return Assignment . create ( lhs , rhs , null ) ; }
Creates a code chunk that assigns value to a preexisting variable with the given name .
29
19
30,478
public static Statement assign ( Expression lhs , Expression rhs , JsDoc jsDoc ) { return Assignment . create ( lhs , rhs , jsDoc ) ; }
Creates a code chunk that assigns and prints jsDoc above the assignment .
36
15
30,479
public static Statement forLoop ( String localVar , Expression limit , Statement body ) { return For . create ( localVar , Expression . number ( 0 ) , limit , Expression . number ( 1 ) , body ) ; }
Creates a code chunk representing a for loop with default values for initial & increment .
45
17
30,480
public static Optional < CompiledTemplates > compile ( final TemplateRegistry registry , final SoyFileSetNode fileSet , boolean developmentMode , ErrorReporter reporter , ImmutableMap < String , SoyFileSupplier > filePathsToSuppliers , SoyTypeRegistry typeRegistry ) { final Stopwatch stopwatch = Stopwatch . createStarted ( ) ; ErrorReporter . Checkpoint checkpoint = reporter . checkpoint ( ) ; if ( reporter . errorsSince ( checkpoint ) ) { return Optional . absent ( ) ; } CompiledTemplateRegistry compilerRegistry = new CompiledTemplateRegistry ( registry ) ; if ( developmentMode ) { CompiledTemplates templates = new CompiledTemplates ( compilerRegistry . getDelegateTemplateNames ( ) , new CompilingClassLoader ( compilerRegistry , fileSet , filePathsToSuppliers , typeRegistry ) ) ; if ( reporter . errorsSince ( checkpoint ) ) { return Optional . absent ( ) ; } // TODO(lukes): consider spawning a thread to load all the generated classes in the background return Optional . of ( templates ) ; } // TODO(lukes): once most internal users have moved to precompilation eliminate this and just // use the 'developmentMode' path above. This hybrid only makes sense for production services // that are doing runtime compilation. Hopefully, this will become an anomaly. List < ClassData > classes = compileTemplates ( compilerRegistry , fileSet , reporter , typeRegistry , new CompilerListener < List < ClassData > > ( ) { final List < ClassData > compiledClasses = new ArrayList <> ( ) ; int numBytes = 0 ; int numFields = 0 ; int numDetachStates = 0 ; @ Override public void onCompile ( ClassData clazz ) { numBytes += clazz . data ( ) . length ; numFields += clazz . numberOfFields ( ) ; numDetachStates += clazz . numberOfDetachStates ( ) ; compiledClasses . add ( clazz ) ; } @ Override public List < ClassData > getResult ( ) { logger . log ( Level . FINE , "Compilation took {0}\n" + " templates: {1}\n" + " classes: {2}\n" + " bytes: {3}\n" + " fields: {4}\n" + " detachStates: {5}" , new Object [ ] { stopwatch . toString ( ) , registry . getAllTemplates ( ) . size ( ) , compiledClasses . size ( ) , numBytes , numFields , numDetachStates } ) ; return compiledClasses ; } } ) ; if ( reporter . errorsSince ( checkpoint ) ) { return Optional . absent ( ) ; } CompiledTemplates templates = new CompiledTemplates ( compilerRegistry . getDelegateTemplateNames ( ) , new MemoryClassLoader ( classes ) ) ; stopwatch . reset ( ) . start ( ) ; templates . loadAll ( compilerRegistry . getTemplateNames ( ) ) ; logger . log ( Level . FINE , "Loaded all classes in {0}" , stopwatch ) ; return Optional . of ( templates ) ; }
Compiles all the templates in the given registry .
678
10
30,481
public void invokeUnchecked ( CodeBuilder cb ) { cb . visitMethodInsn ( opcode ( ) , owner ( ) . internalName ( ) , method ( ) . getName ( ) , method ( ) . getDescriptor ( ) , // This is for whether the methods owner is an interface. This is mostly to handle java8 // default methods on interfaces. We don't care about those currently, but ASM requires // this. opcode ( ) == Opcodes . INVOKEINTERFACE ) ; }
Writes an invoke instruction for this method to the given adapter . Useful when the expression is not useful for representing operations . For example explicit dup operations are awkward in the Expression api .
110
36
30,482
@ Deprecated protected static SoyData createFromExistingData ( Object obj ) { if ( obj instanceof SoyData ) { return ( SoyData ) obj ; } else if ( obj instanceof Map < ? , ? > ) { @ SuppressWarnings ( "unchecked" ) Map < String , ? > objCast = ( Map < String , ? > ) obj ; return new SoyMapData ( objCast ) ; } else if ( obj instanceof Iterable < ? > ) { return new SoyListData ( ( Iterable < ? > ) obj ) ; } else if ( obj instanceof Future < ? > ) { // Note: In the old SoyData, we don't support late-resolution of Futures. We immediately // resolve the Future object here. For late-resolution, use SoyValueConverter.convert(). try { return createFromExistingData ( ( ( Future < ? > ) obj ) . get ( ) ) ; } catch ( InterruptedException e ) { throw new SoyDataException ( "Encountered InterruptedException when resolving Future object." , e ) ; } catch ( ExecutionException e ) { throw new SoyDataException ( "Encountered ExecutionException when resolving Future object." , e ) ; } } else { SoyValue soyValue = SoyValueConverter . INSTANCE . convert ( obj ) . resolve ( ) ; if ( soyValue instanceof SoyData ) { return ( SoyData ) soyValue ; } throw new SoyDataException ( "Attempting to convert unrecognized object to Soy data (object type " + obj . getClass ( ) . getName ( ) + ")." ) ; } }
Creates deprecated SoyData objects from standard Java data structures .
346
12
30,483
public static boolean hasPlrselPart ( List < SoyMsgPart > msgParts ) { for ( SoyMsgPart origMsgPart : msgParts ) { if ( origMsgPart instanceof SoyMsgPluralPart || origMsgPart instanceof SoyMsgSelectPart ) { return true ; } } return false ; }
Checks whether a given list of msg parts has any plural or select parts .
65
16
30,484
public void set ( int index , SoyData value ) { if ( index == list . size ( ) ) { list . add ( ensureValidValue ( value ) ) ; } else { list . set ( index , ensureValidValue ( value ) ) ; } }
Sets a data value at a given index .
54
10
30,485
@ Override public SoyData get ( int index ) { try { return list . get ( index ) ; } catch ( IndexOutOfBoundsException ioobe ) { return null ; } }
Gets the data value at a given index .
40
10
30,486
public static String getDidYouMeanMessage ( Iterable < String > allNames , String wrongName ) { String closestName = getClosest ( allNames , wrongName ) ; if ( closestName != null ) { return String . format ( " Did you mean '%s'?" , closestName ) ; } return "" ; }
Given a collection of strings and a name that isn t contained in it . Return a message that suggests one of the names .
71
25
30,487
private static int distance ( String s , String t , int maxDistance ) { // create two work vectors of integer distances // it is possible to reduce this to only one array, but performance isn't that important here. // We could also avoid calculating a lot of the entries by taking maxDistance into account in // the inner loop. This would only be worth optimizing if it showed up in a profile. int [ ] v0 = new int [ t . length ( ) + 1 ] ; int [ ] v1 = new int [ t . length ( ) + 1 ] ; // initialize v0 (the previous row of distances) // this row is A[0][i]: edit distance for an empty s // the distance is just the number of characters to delete from t for ( int i = 0 ; i < v0 . length ; i ++ ) { v0 [ i ] = i ; } for ( int i = 0 ; i < s . length ( ) ; i ++ ) { // calculate v1 (current row distances) from the previous row v0 // first element of v1 is A[i+1][0] // edit distance is delete (i+1) chars from s to match empty t v1 [ 0 ] = i + 1 ; int bestThisRow = v1 [ 0 ] ; char sChar = Ascii . toLowerCase ( s . charAt ( i ) ) ; // use formula to fill in the rest of the row for ( int j = 0 ; j < t . length ( ) ; j ++ ) { char tChar = Ascii . toLowerCase ( t . charAt ( j ) ) ; v1 [ j + 1 ] = Math . min ( v1 [ j ] + 1 , // deletion Math . min ( v0 [ j + 1 ] + 1 , // insertion v0 [ j ] + ( ( sChar == tChar ) ? 0 : 1 ) ) ) ; // substitution bestThisRow = Math . min ( bestThisRow , v1 [ j + 1 ] ) ; } if ( bestThisRow > maxDistance ) { // if we couldn't possibly do better than maxDistance, stop trying. return maxDistance + 1 ; } // swap v1 (current row) to v0 (previous row) for next iteration. no need to clear previous // row since we always update all of v1 on each iteration. int [ ] tmp = v0 ; v0 = v1 ; v1 = tmp ; } // The best answer is the last slot in v0 (due to the swap on the last iteration) return v0 [ t . length ( ) ] ; }
Performs a case insensitive Levenshtein edit distance based on the 2 rows implementation .
551
18
30,488
public static String formatErrors ( Iterable < SoyError > errors ) { int numErrors = 0 ; int numWarnings = 0 ; for ( SoyError error : errors ) { if ( error . isWarning ( ) ) { numWarnings ++ ; } else { numErrors ++ ; } } if ( numErrors + numWarnings == 0 ) { throw new IllegalArgumentException ( "cannot format 0 errors" ) ; } StringBuilder sb = new StringBuilder ( numErrors == 0 ? "warnings" : "errors" ) . append ( " during Soy compilation\n" ) ; Joiner . on ( ' ' ) . appendTo ( sb , errors ) ; if ( numErrors > 0 ) { formatNumber ( numErrors , "error" , sb ) ; } if ( numWarnings > 0 ) { if ( numErrors > 0 ) { sb . append ( ' ' ) ; } formatNumber ( numWarnings , "warning" , sb ) ; } return sb . append ( ' ' ) . toString ( ) ; }
Formats the errors in a standard way for displaying to a user .
238
14
30,489
public void prependKeyToDataPath ( String key ) { if ( dataPath == null ) { dataPath = key ; } else { dataPath = key + ( ( dataPath . charAt ( 0 ) == ' ' ) ? "" : "." ) + dataPath ; } }
Prepends a key to the data path where this error occurred . E . g . if the dataPath was previously foo . goo and the key to prepend is boo then the new data path will be boo . foo . goo .
60
49
30,490
@ Memoized public Type type ( ) { int dotIndex = identifier ( ) . indexOf ( ' ' ) ; if ( dotIndex == 0 ) { checkArgument ( BaseUtils . isIdentifierWithLeadingDot ( identifier ( ) ) ) ; return Type . DOT_IDENT ; } else { checkArgument ( BaseUtils . isDottedIdentifier ( identifier ( ) ) ) ; return dotIndex == - 1 ? Type . SINGLE_IDENT : Type . DOTTED_IDENT ; } }
This field is only rarely accessed memoize it .
111
10
30,491
public Identifier extractPartAfterLastDot ( ) { String part = BaseUtils . extractPartAfterLastDot ( identifier ( ) ) ; return Identifier . create ( part , location ( ) . offsetStartCol ( identifier ( ) . length ( ) - part . length ( ) ) ) ; }
Gets the part after the last dot in a dotted identifier . If there are no dots returns the whole identifier .
64
23
30,492
@ Nullable public static PrimitiveNode convertPrimitiveDataToExpr ( PrimitiveData primitiveData , SourceLocation location ) { if ( primitiveData instanceof StringData ) { return new StringNode ( primitiveData . stringValue ( ) , QuoteStyle . SINGLE , location ) ; } else if ( primitiveData instanceof BooleanData ) { return new BooleanNode ( primitiveData . booleanValue ( ) , location ) ; } else if ( primitiveData instanceof IntegerData ) { // NOTE: We only support numbers in the range of JS [MIN_SAFE_INTEGER, MAX_SAFE_INTEGER] if ( ! IntegerNode . isInRange ( primitiveData . longValue ( ) ) ) { return null ; } else { return new IntegerNode ( primitiveData . longValue ( ) , location ) ; } } else if ( primitiveData instanceof FloatData ) { return new FloatNode ( primitiveData . floatValue ( ) , location ) ; } else if ( primitiveData instanceof NullData ) { return new NullNode ( location ) ; } else { throw new IllegalArgumentException ( ) ; } }
Converts a primitive data object into a primitive expression node .
236
12
30,493
public static PrimitiveData convertPrimitiveExprToData ( PrimitiveNode primitiveNode ) { if ( primitiveNode instanceof StringNode ) { return StringData . forValue ( ( ( StringNode ) primitiveNode ) . getValue ( ) ) ; } else if ( primitiveNode instanceof BooleanNode ) { return BooleanData . forValue ( ( ( BooleanNode ) primitiveNode ) . getValue ( ) ) ; } else if ( primitiveNode instanceof IntegerNode ) { return IntegerData . forValue ( ( ( IntegerNode ) primitiveNode ) . getValue ( ) ) ; } else if ( primitiveNode instanceof FloatNode ) { return FloatData . forValue ( ( ( FloatNode ) primitiveNode ) . getValue ( ) ) ; } else if ( primitiveNode instanceof NullNode ) { return NullData . INSTANCE ; } else { throw new IllegalArgumentException ( ) ; } }
Converts a primitive expression node into a primitive data object .
187
12
30,494
public static ImmutableMap < String , PrimitiveData > convertCompileTimeGlobalsMap ( Map < String , ? > compileTimeGlobalsMap ) { ImmutableMap . Builder < String , PrimitiveData > resultMapBuilder = ImmutableMap . builder ( ) ; for ( Map . Entry < String , ? > entry : compileTimeGlobalsMap . entrySet ( ) ) { Object valueObj = entry . getValue ( ) ; PrimitiveData value ; boolean isValidValue = true ; try { SoyValue value0 = SoyValueConverter . INSTANCE . convert ( valueObj ) . resolve ( ) ; if ( ! ( value0 instanceof PrimitiveData ) ) { isValidValue = false ; } value = ( PrimitiveData ) value0 ; } catch ( SoyDataException sde ) { isValidValue = false ; value = null ; // make compiler happy } if ( ! isValidValue ) { throw new IllegalArgumentException ( "Compile-time globals map contains invalid value: " + valueObj + " for key: " + entry . getKey ( ) ) ; } resultMapBuilder . put ( entry . getKey ( ) , value ) ; } return resultMapBuilder . build ( ) ; }
Converts a compile - time globals map in user - provided format into one in the internal format .
263
21
30,495
boolean shouldCheckConformanceFor ( String filePath ) { for ( String whitelistedPath : getWhitelistedPaths ( ) ) { if ( filePath . contains ( whitelistedPath ) ) { return false ; } } ImmutableList < String > onlyApplyToPaths = getOnlyApplyToPaths ( ) ; if ( onlyApplyToPaths . isEmpty ( ) ) { return true ; } // If only_apply_to field is presented in the configuration, check it. for ( String onlyApplyToPath : onlyApplyToPaths ) { if ( filePath . contains ( onlyApplyToPath ) ) { return true ; } } return false ; }
A file should be checked against a rule unless it contains one of the whitelisted paths .
144
19
30,496
private static boolean isEmpty ( MsgNode msg ) { for ( SoyNode child : msg . getChildren ( ) ) { if ( child instanceof RawTextNode && ( ( RawTextNode ) child ) . getRawText ( ) . isEmpty ( ) ) { continue ; } return false ; } return true ; }
If the only children are empty raw text nodes then the node is empty .
67
15
30,497
public void setEscapingDirectives ( SoyNode node , Context context , List < EscapingMode > escapingModes ) { Preconditions . checkArgument ( ( node instanceof PrintNode ) || ( node instanceof CallNode ) || ( node instanceof MsgFallbackGroupNode ) , "Escaping directives may only be set for {print}, {msg}, or {call} nodes" ) ; if ( escapingModes != null ) { nodeToEscapingModes . put ( node , ImmutableList . copyOf ( escapingModes ) ) ; } nodeToContext . put ( node , context ) ; }
Records inferred escaping modes so a directive can be later added to the Soy parse tree .
131
18
30,498
public ImmutableList < EscapingMode > getEscapingModesForNode ( SoyNode node ) { ImmutableList < EscapingMode > modes = nodeToEscapingModes . get ( node ) ; if ( modes == null ) { modes = ImmutableList . of ( ) ; } return modes ; }
The escaping modes for the print command with the given ID in the order in which they should be applied .
66
21
30,499
static SoyMsgBundle parseXliffTargetMsgs ( String xliffContent ) throws SAXException { // Get a SAX parser. SAXParserFactory saxParserFactory = SAXParserFactory . newInstance ( ) ; SAXParser saxParser ; try { saxParser = saxParserFactory . newSAXParser ( ) ; } catch ( ParserConfigurationException pce ) { throw new AssertionError ( "Could not get SAX parser for XML." ) ; } // Construct the handler for SAX parsing. XliffSaxHandler xliffSaxHandler = new XliffSaxHandler ( ) ; // Parse the XLIFF content. try { saxParser . parse ( new InputSource ( new StringReader ( xliffContent ) ) , xliffSaxHandler ) ; } catch ( IOException e ) { throw new AssertionError ( "Should not fail in reading a string." ) ; } // Build a SoyMsgBundle from the parsed data (stored in xliffSaxHandler). return new SoyMsgBundleImpl ( xliffSaxHandler . getTargetLocaleString ( ) , xliffSaxHandler . getMsgs ( ) ) ; }
Parses the content of a translated XLIFF file and creates a SoyMsgBundle .
252
19