idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
30,700 | public StackTraceElement createStackTraceElement ( SourceLocation srcLocation ) { return new StackTraceElement ( /* declaringClass= */ soyFileHeaderInfo . namespace , // The partial template name begins with a '.' that causes the stack trace element to // print "namespace..templateName" otherwise. /* methodName= */ partialTemplateName . substring ( 1 ) , srcLocation . getFileName ( ) , srcLocation . getBeginLine ( ) ) ; } | Construct a StackTraceElement that will point to the given source location of the current template . | 99 | 19 |
30,701 | protected void configure ( String [ ] args ) throws IOException { for ( String arg : args ) { if ( arg . startsWith ( "--input=" ) ) { FileRef ref = createInput ( ) ; ref . setPath ( arg . substring ( arg . indexOf ( ' ' ) + 1 ) ) ; } else if ( arg . startsWith ( "--output=" ) ) { FileRef ref = createOutput ( ) ; ref . setPath ( arg . substring ( arg . indexOf ( ' ' ) + 1 ) ) ; } else if ( arg . startsWith ( "--libdefined=" ) ) { FunctionNamePredicate libdefined = new FunctionNamePredicate ( ) ; libdefined . setPattern ( arg . substring ( arg . indexOf ( ' ' ) + 1 ) ) ; addConfiguredLibdefined ( libdefined ) ; } else { throw new IllegalArgumentException ( arg ) ; } } } | Setup method to read arguments and setup initial configuration . | 197 | 10 |
30,702 | @ Override public void execute ( ) { super . execute ( ) ; if ( output == null ) { System . err . println ( "Please add an <output> for the <" + getTaskName ( ) + "> at " + this . getLocation ( ) ) ; return ; } // Gather output in a buffer rather than generating a bad file with a valid timestamp. StringBuilder sb = new StringBuilder ( ) ; // Output the source files that use the helper functions first, so we get the appropriate file // overviews and copyright headers. for ( FileRef input : inputs ) { try { boolean inGeneratedCode = false ; for ( String line : Files . readLines ( input . file , Charsets . UTF_8 ) ) { // Skip code between generated code markers so that this transformation is idempotent. // We can run an old output through this class, and get the latest version out. if ( inGeneratedCode ) { if ( GENERATED_CODE_END_MARKER . equals ( line . trim ( ) ) ) { inGeneratedCode = false ; } } else if ( GENERATED_CODE_START_MARKER . equals ( line . trim ( ) ) ) { inGeneratedCode = true ; } else { sb . append ( line ) . append ( ' ' ) ; } } } catch ( IOException ex ) { System . err . println ( "Failed to read " + input . file ) ; ex . printStackTrace ( ) ; return ; } } // Generate helper functions for escape directives. generateCode ( availableIdentifiers , sb ) ; // Output a file now that we know generation hasn't failed. try { Files . asCharSink ( output . file , Charsets . UTF_8 ) . write ( sb ) ; } catch ( IOException ex ) { // Make sure an abortive write does not leave a file w output . file . delete ( ) ; } } | Called to actually build the output by Ant . | 421 | 10 |
30,703 | protected void writeStringLiteral ( String value , StringBuilder out ) { out . append ( ' ' ) . append ( escapeOutputString ( value ) ) . append ( ' ' ) ; } | Appends a string literal with the given value onto the given buffer . | 41 | 14 |
30,704 | private void writeUnsafeStringLiteral ( char value , StringBuilder out ) { if ( ! isPrintable ( value ) ) { // Don't emit non-Latin characters or control characters since they don't roundtrip well. out . append ( String . format ( value >= 0x100 ? "'\\u%04x'" : "'\\x%02x'" , ( int ) value ) ) ; } else { out . append ( ' ' ) . append ( escapeOutputString ( String . valueOf ( value ) ) ) . append ( ' ' ) ; } } | Appends a string literal which may not be printable with the given value onto the given buffer . | 120 | 20 |
30,705 | public static Expression extensionField ( FieldDescriptor desc ) { String jsExtensionImport = ProtoUtils . getJsExtensionImport ( desc ) ; String jsExtensionName = ProtoUtils . getJsExtensionName ( desc ) ; return symbolWithNamespace ( jsExtensionImport , jsExtensionName ) ; } | Returns the field containing the extension object for the given field descriptor . | 69 | 13 |
30,706 | public static Expression protoToSanitizedContentConverterFunction ( Descriptor messageType ) { return GoogRequire . create ( NodeContentKinds . toJsUnpackFunction ( messageType ) ) . reference ( ) ; } | Returns a function that can unpack safe proto types into sanitized content types .. | 49 | 16 |
30,707 | public static Expression protoConstructor ( SoyProtoType type ) { return GoogRequire . create ( type . getNameForBackend ( SoyBackendKind . JS_SRC ) ) . reference ( ) ; } | Returns the constructor for the proto . | 47 | 7 |
30,708 | public static Expression sanitizedContentType ( SanitizedContentKind kind ) { return GoogRequire . create ( NodeContentKinds . toJsSanitizedContentCtorName ( kind ) ) . reference ( ) ; } | Returns the js type for the sanitized content object corresponding to the given ContentKind . | 46 | 17 |
30,709 | private static Expression symbolWithNamespace ( String requireSymbol , String fullyQualifiedSymbol ) { GoogRequire require = GoogRequire . create ( requireSymbol ) ; if ( fullyQualifiedSymbol . equals ( require . symbol ( ) ) ) { return require . reference ( ) ; } String ident = fullyQualifiedSymbol . substring ( require . symbol ( ) . length ( ) + 1 ) ; return require . dotAccess ( ident ) ; } | Returns a code chunk that accesses the given symbol . | 100 | 11 |
30,710 | private boolean areChildrenComputableAsJsExprs ( ParentSoyNode < ? > node ) { for ( SoyNode child : node . getChildren ( ) ) { if ( canSkipChild ( child ) ) { continue ; } if ( ! visit ( child ) ) { return false ; } } return true ; } | Private helper to check whether all children of a given parent node satisfy IsComputableAsJsExprsVisitor . | 67 | 24 |
30,711 | private ParseResult parseWithVersions ( ) throws IOException { List < TemplateMetadata > templateMetadatas = new ArrayList <> ( ) ; for ( CompilationUnitAndKind unit : compilationUnits ( ) ) { templateMetadatas . addAll ( TemplateMetadataSerializer . templatesFromCompilationUnit ( unit . compilationUnit ( ) , unit . fileKind ( ) , typeRegistry ( ) , unit . filePath ( ) , errorReporter ( ) ) ) ; } IdGenerator nodeIdGen = ( cache ( ) != null ) ? cache ( ) . getNodeIdGenerator ( ) : new IncrementingIdGenerator ( ) ; SoyFileSetNode soyTree = new SoyFileSetNode ( nodeIdGen . genId ( ) , nodeIdGen ) ; boolean filesWereSkipped = false ; // TODO(lukes): there are other places in the compiler (autoescaper) which may use the id // generator but fail to lock on it. Eliminate the id system to avoid this whole issue. synchronized ( nodeIdGen ) { // Avoid using the same ID generator in multiple threads. for ( SoyFileSupplier fileSupplier : soyFileSuppliers ( ) . values ( ) ) { SoyFileSupplier . Version version = fileSupplier . getVersion ( ) ; VersionedFile cachedFile = cache ( ) != null ? cache ( ) . get ( fileSupplier . getFilePath ( ) , version ) : null ; SoyFileNode node ; if ( cachedFile == null ) { node = parseSoyFileHelper ( fileSupplier , nodeIdGen ) ; // TODO(b/19269289): implement error recovery and keep on trucking in order to display // as many errors as possible. Currently, the later passes just spew NPEs if run on // a malformed parse tree. if ( node == null ) { filesWereSkipped = true ; continue ; } // Run passes that are considered part of initial parsing. passManager ( ) . runSingleFilePasses ( node , nodeIdGen ) ; // Run passes that check the tree. if ( cache ( ) != null ) { cache ( ) . put ( fileSupplier . getFilePath ( ) , VersionedFile . of ( node , version ) ) ; } } else { node = cachedFile . file ( ) ; } for ( TemplateNode template : node . getChildren ( ) ) { templateMetadatas . add ( TemplateMetadata . fromTemplate ( template ) ) ; } soyTree . addChild ( node ) ; } TemplateRegistry registry = new TemplateRegistry ( templateMetadatas , errorReporter ( ) ) ; // Run passes that check the tree iff we successfully parsed every file. if ( ! filesWereSkipped ) { passManager ( ) . runWholeFilesetPasses ( soyTree , registry ) ; } return ParseResult . create ( soyTree , registry ) ; } } | Parses a set of Soy files returning a structure containing the parse tree and template registry . | 624 | 19 |
30,712 | private boolean areChildrenComputableAsPyExprs ( ParentSoyNode < ? > node ) { for ( SoyNode child : node . getChildren ( ) ) { // Note: Save time by not visiting RawTextNode and PrintNode children. if ( ! ( child instanceof RawTextNode ) && ! ( child instanceof PrintNode ) ) { if ( ! visit ( child ) ) { return false ; } } } return true ; } | Private helper to check whether all SoyNode children of a given parent node satisfy IsComputableAsPyExprVisitor . ExprNode children are assumed to be computable as PyExprs . | 93 | 41 |
30,713 | public TypeInfo registerInnerClass ( String simpleName , int accessModifiers ) { classNames . claimName ( simpleName ) ; TypeInfo innerClass = outer . innerClass ( simpleName ) ; innerClassesAccessModifiers . put ( innerClass , accessModifiers ) ; return innerClass ; } | Register the given name as an inner class with the given access modifiers . | 64 | 14 |
30,714 | public void add ( ClassData classData ) { checkRegistered ( classData . type ( ) ) ; innerClasses . put ( classData . type ( ) , classData ) ; } | Adds the data for an inner class . | 39 | 8 |
30,715 | public void registerAsInnerClass ( ClassVisitor visitor , TypeInfo innerClass ) { checkRegistered ( innerClass ) ; doRegister ( visitor , innerClass ) ; } | Registers this factory as an inner class on the given class writer . | 36 | 14 |
30,716 | public void registerAllInnerClasses ( ClassVisitor visitor ) { for ( Map . Entry < TypeInfo , Integer > entry : innerClassesAccessModifiers . entrySet ( ) ) { TypeInfo innerClass = entry . getKey ( ) ; doRegister ( visitor , innerClass ) ; } } | Registers all inner classes to the given outer class . | 64 | 11 |
30,717 | public SoyMsgBundle compact ( SoyMsgBundle input ) { ImmutableList . Builder < SoyMsg > builder = ImmutableList . builder ( ) ; for ( SoyMsg msg : input ) { ImmutableList < SoyMsgPart > parts = compactParts ( msg . getParts ( ) ) ; builder . add ( SoyMsg . builder ( ) . setId ( msg . getId ( ) ) . setLocaleString ( msg . getLocaleString ( ) ) . setIsPlrselMsg ( MsgPartUtils . hasPlrselPart ( parts ) ) . setParts ( parts ) . build ( ) ) ; } return new RenderOnlySoyMsgBundleImpl ( input . getLocaleString ( ) , builder . build ( ) ) ; } | Returns a more memory - efficient version of the internal message bundle . | 163 | 13 |
30,718 | private ImmutableList < SoyMsgPart > compactParts ( ImmutableList < SoyMsgPart > parts ) { ImmutableList . Builder < SoyMsgPart > builder = ImmutableList . builder ( ) ; for ( SoyMsgPart part : parts ) { builder . add ( compactPart ( part ) ) ; } return builder . build ( ) ; } | Compacts a set of message parts . | 73 | 8 |
30,719 | private SoyMsgPart compactPart ( SoyMsgPart part ) { if ( part instanceof SoyMsgPluralPart ) { part = compactPlural ( ( SoyMsgPluralPart ) part ) ; } else if ( part instanceof SoyMsgSelectPart ) { part = compactSelect ( ( SoyMsgSelectPart ) part ) ; } else if ( part instanceof SoyMsgPlaceholderPart ) { part = compactPlaceholder ( ( SoyMsgPlaceholderPart ) part ) ; } // Now intern the message part. return intern ( part ) ; } | Compacts a single message part . | 113 | 7 |
30,720 | public void claimName ( String name ) { checkName ( name ) ; if ( names . add ( name , 1 ) != 0 ) { names . remove ( name ) ; // give a slightly better error message in this case if ( reserved . contains ( name ) ) { throw new IllegalArgumentException ( "Tried to claim a reserved name: " + name ) ; } throw new IllegalArgumentException ( "Name: " + name + " was already claimed!" ) ; } } | Registers the name throwing an IllegalArgumentException if it has already been registered . | 101 | 17 |
30,721 | public void reserve ( String name ) { checkName ( name ) ; // if this is new if ( reserved . add ( name ) ) { // add it to names, so that generateName will still work for reserved names (they will just // get suffixes). if ( ! names . add ( name ) ) { names . remove ( name ) ; throw new IllegalArgumentException ( "newly reserved name: " + name + " was already used!" ) ; } } } | Reserves the name useful for keywords . | 99 | 8 |
30,722 | public String generateName ( String name ) { checkName ( name ) ; names . add ( name ) ; int count = names . count ( name ) ; if ( count == 1 ) { return name ; } return name + collisionSeparator + ( count - 1 ) ; } | Returns a name based on the supplied one that is guaranteed to be unique among the names that have been returned by this method . | 58 | 25 |
30,723 | private static void addCodeToRequireCss ( JsDoc . Builder header , SoyFileNode soyFile ) { SortedSet < String > requiredCssNamespaces = new TreeSet <> ( ) ; requiredCssNamespaces . addAll ( soyFile . getRequiredCssNamespaces ( ) ) ; for ( TemplateNode template : soyFile . getChildren ( ) ) { requiredCssNamespaces . addAll ( template . getRequiredCssNamespaces ( ) ) ; } // NOTE: CSS requires in JS can only be done on a file by file basis at this time. Perhaps in // the future, this might be supported per function. for ( String requiredCssNamespace : requiredCssNamespaces ) { header . addParameterizedAnnotation ( "requirecss" , requiredCssNamespace ) ; } } | Appends requirecss jsdoc tags in the file header section . | 176 | 13 |
30,724 | private Expression coerceTypeForSwitchComparison ( ExprRootNode expr ) { Expression switchOn = translateExpr ( expr ) ; SoyType type = expr . getType ( ) ; // If the type is possibly a sanitized content type then we need to toString it. if ( SoyTypes . makeNullable ( StringType . getInstance ( ) ) . isAssignableFrom ( type ) || type . equals ( AnyType . getInstance ( ) ) || type . equals ( UnknownType . getInstance ( ) ) ) { CodeChunk . Generator codeGenerator = templateTranslationContext . codeGenerator ( ) ; Expression tmp = codeGenerator . declarationBuilder ( ) . setRhs ( switchOn ) . build ( ) . ref ( ) ; return Expression . ifExpression ( GOOG_IS_OBJECT . call ( tmp ) , tmp . dotAccess ( "toString" ) . call ( ) ) . setElse ( tmp ) . build ( codeGenerator ) ; } // For everything else just pass through. switching on objects/collections is unlikely to // have reasonably defined behavior. return switchOn ; } | to strings . | 238 | 3 |
30,725 | private String genParamsRecordType ( TemplateNode node ) { Set < String > paramNames = new HashSet <> ( ) ; // Generate members for explicit params. Map < String , String > record = new LinkedHashMap <> ( ) ; for ( TemplateParam param : node . getParams ( ) ) { JsType jsType = getJsTypeForParamForDeclaration ( param . type ( ) ) ; record . put ( param . name ( ) , jsType . typeExprForRecordMember ( /* isOptional= */ ! param . isRequired ( ) ) ) ; for ( GoogRequire require : jsType . getGoogRequires ( ) ) { // TODO(lukes): switch these to requireTypes jsCodeBuilder . addGoogRequire ( require ) ; } paramNames . add ( param . name ( ) ) ; } // Do the same for indirect params, if we can find them. // If there's a conflict between the explicitly-declared type, and the type // inferred from the indirect params, then the explicit type wins. // Also note that indirect param types may not be inferrable if the target // is not in the current compilation file set. IndirectParamsInfo ipi = new IndirectParamsCalculator ( templateRegistry ) . calculateIndirectParams ( templateRegistry . getMetadata ( node ) ) ; // If there are any calls outside of the file set, then we can't know // the complete types of any indirect params. In such a case, we can simply // omit the indirect params from the function type signature, since record // types in JS allow additional undeclared fields to be present. if ( ! ipi . mayHaveIndirectParamsInExternalCalls && ! ipi . mayHaveIndirectParamsInExternalDelCalls ) { for ( String indirectParamName : ipi . indirectParamTypes . keySet ( ) ) { if ( paramNames . contains ( indirectParamName ) ) { continue ; } Collection < SoyType > paramTypes = ipi . indirectParamTypes . get ( indirectParamName ) ; SoyType combinedType = SoyTypes . computeLowestCommonType ( typeRegistry , paramTypes ) ; // Note that Union folds duplicate types and flattens unions, so if // the combinedType is already a union this will do the right thing. // TODO: detect cases where nullable is not needed (requires flow // analysis to determine if the template is always called.) SoyType indirectParamType = typeRegistry . getOrCreateUnionType ( combinedType , NullType . getInstance ( ) ) ; JsType jsType = getJsTypeForParamForDeclaration ( indirectParamType ) ; // NOTE: we do not add goog.requires for indirect types. This is because it might introduce // strict deps errors. This should be fine though since the transitive soy template that // actually has the param will add them. record . put ( indirectParamName , jsType . typeExprForRecordMember ( /* isOptional= */ true ) ) ; } } StringBuilder sb = new StringBuilder ( ) ; sb . append ( "{\n * " ) ; Joiner . on ( ",\n * " ) . withKeyValueSeparator ( ": " ) . appendTo ( sb , record ) ; // trailing comma in record is important in case the last record member is the // unknown type sb . append ( ",\n * }" ) ; return sb . toString ( ) ; } | Generate the JSDoc for the opt_data parameter . | 746 | 13 |
30,726 | @ CheckReturnValue protected Statement genParamTypeChecks ( TemplateNode node , String alias ) { ImmutableList . Builder < Statement > declarations = ImmutableList . builder ( ) ; for ( TemplateParam param : node . getAllParams ( ) ) { String paramName = param . name ( ) ; SoyType paramType = param . type ( ) ; CodeChunk . Generator generator = templateTranslationContext . codeGenerator ( ) ; Expression paramChunk = genCodeForParamAccess ( paramName , param ) ; JsType jsType = getJsTypeForParamTypeCheck ( paramType ) ; // The opt_param.name value that will be type-tested. String paramAlias = genParamAlias ( paramName ) ; Expression coerced = jsType . getValueCoercion ( paramChunk , generator ) ; if ( coerced != null ) { // since we have coercion logic, dump into a temporary paramChunk = generator . declarationBuilder ( ) . setRhs ( coerced ) . build ( ) . ref ( ) ; } if ( param . hasDefault ( ) ) { if ( coerced == null ) { paramChunk = generator . declarationBuilder ( ) . setRhs ( paramChunk ) . build ( ) . ref ( ) ; } declarations . add ( genParamDefault ( param , paramChunk , alias , jsType , /* declareStatic= */ true ) ) ; } // The param value to assign Expression value ; Optional < Expression > soyTypeAssertion = jsType . getSoyTypeAssertion ( paramChunk , paramName , generator ) ; // The type-cast expression. if ( soyTypeAssertion . isPresent ( ) ) { value = soyTypeAssertion . get ( ) ; } else { value = paramChunk ; } VariableDeclaration . Builder declarationBuilder = VariableDeclaration . builder ( paramAlias ) . setRhs ( value ) . setGoogRequires ( jsType . getGoogRequires ( ) ) ; declarationBuilder . setJsDoc ( JsDoc . builder ( ) . addParameterizedAnnotation ( "type" , getJsTypeForParamForDeclaration ( paramType ) . typeExpr ( ) ) . build ( ) ) ; VariableDeclaration declaration = declarationBuilder . build ( ) ; declarations . add ( declaration ) ; templateTranslationContext . soyToJsVariableMappings ( ) // TODO(lukes): this should really be declartion.ref() but we cannot do that until // everything is on the code chunk api. . put ( paramName , id ( paramAlias ) ) ; } return Statement . of ( declarations . build ( ) ) ; } | Generate code to verify the runtime types of the input params . Also typecasts the input parameters and assigns them to local variables for use in the template . | 557 | 31 |
30,727 | public static PluginResolver nullResolver ( Mode mode , ErrorReporter reporter ) { return new PluginResolver ( mode , ImmutableMap . of ( ) , ImmutableMap . of ( ) , ImmutableMap . of ( ) , reporter ) ; } | Returns an empty resolver . Useful for tests or situations where it is known that no plugins will be needed . | 54 | 22 |
30,728 | public SoyPrintDirective lookupPrintDirective ( String name , int numArgs , SourceLocation location ) { SoyPrintDirective soyPrintDirective = printDirectives . get ( name ) ; if ( soyPrintDirective == null ) { reportMissing ( location , "print directive" , name , printDirectives . keySet ( ) ) ; soyPrintDirective = createPlaceholderPrintDirective ( name , numArgs ) ; } checkNumArgs ( "print directive" , soyPrintDirective . getValidArgsSizes ( ) , numArgs , location ) ; warnIfDeprecated ( name , soyPrintDirective , location ) ; return soyPrintDirective ; } | Returns a print directive with the given name and arity . | 141 | 12 |
30,729 | public Object lookupSoyFunction ( String name , int numArgs , SourceLocation location ) { Object soyFunction = functions . get ( name ) ; if ( soyFunction == null ) { reportMissing ( location , "function" , name , functions . keySet ( ) ) ; return ERROR_PLACEHOLDER_FUNCTION ; } Set < Integer > validArgsSize ; if ( soyFunction instanceof SoyFunction ) { validArgsSize = ( ( SoyFunction ) soyFunction ) . getValidArgsSizes ( ) ; } else { validArgsSize = getValidArgsSizes ( soyFunction . getClass ( ) . getAnnotation ( SoyFunctionSignature . class ) . value ( ) ) ; } checkNumArgs ( "function" , validArgsSize , numArgs , location ) ; warnIfDeprecated ( name , soyFunction , location ) ; return soyFunction ; } | Returns a function with the given name and arity . | 185 | 11 |
30,730 | public void setPrintDirective ( SoyPrintDirective printDirective ) { checkState ( this . printDirective == null , "setPrintDirective has already been called" ) ; checkArgument ( name . identifier ( ) . equals ( printDirective . getName ( ) ) ) ; this . printDirective = checkNotNull ( printDirective ) ; } | Sets the print directive . | 78 | 6 |
30,731 | LocalVariableStack addVariable ( String name , PyExpr varExpression ) { Preconditions . checkState ( ! localVarExprs . isEmpty ( ) ) ; localVarExprs . peek ( ) . put ( name , varExpression ) ; return this ; } | Adds a variable to the current reference frame . | 60 | 9 |
30,732 | public Context derive ( HtmlContext state ) { return state == this . state ? this : toBuilder ( ) . withState ( state ) . build ( ) ; } | Returns a context that differs only in the state . | 35 | 10 |
30,733 | public Context derive ( JsFollowingSlash slashType ) { return slashType == this . slashType ? this : toBuilder ( ) . withSlashType ( slashType ) . build ( ) ; } | Returns a context that differs only in the following slash . | 43 | 11 |
30,734 | public Context derive ( UriPart uriPart ) { return uriPart == this . uriPart ? this : toBuilder ( ) . withUriPart ( uriPart ) . build ( ) ; } | Returns a context that differs only in the uri part . | 44 | 12 |
30,735 | public Context derive ( HtmlHtmlAttributePosition htmlHtmlAttributePosition ) { return htmlHtmlAttributePosition == this . htmlHtmlAttributePosition ? this : toBuilder ( ) . withHtmlHtmlAttributePosition ( htmlHtmlAttributePosition ) . build ( ) ; } | Returns a context that differs only in the HTML attribute containing HTML position . | 59 | 14 |
30,736 | public Context getContextAfterDynamicValue ( ) { // TODO: If the context is JS, perhaps this should return JsFollowingSlash.UNKNOWN. Right now // we assume that the dynamic value is also an expression, but JsFollowingSlash.UNKNOWN would // account for things that end in semicolons (since the next slash could be either a regex OR a // division op). if ( state == HtmlContext . JS ) { switch ( slashType ) { case DIV_OP : case UNKNOWN : return this ; case REGEX : return derive ( JsFollowingSlash . DIV_OP ) ; case NONE : throw new IllegalStateException ( slashType . name ( ) ) ; } } else if ( state == HtmlContext . HTML_BEFORE_OPEN_TAG_NAME || state == HtmlContext . HTML_BEFORE_CLOSE_TAG_NAME ) { // We assume ElementType.NORMAL, because filterHtmlElementName filters dangerous tag names. return toBuilder ( ) . withState ( HtmlContext . HTML_TAG_NAME ) . withElType ( ElementType . NORMAL ) . build ( ) ; } else if ( state == HtmlContext . HTML_TAG ) { // To handle a substitution that starts an attribute name <tag {$attrName}=...> return toBuilder ( ) . withState ( HtmlContext . HTML_ATTRIBUTE_NAME ) . withAttrType ( AttributeType . PLAIN_TEXT ) . build ( ) ; } else if ( uriPart == UriPart . START ) { if ( uriType == UriType . TRUSTED_RESOURCE ) { return derive ( UriPart . AUTHORITY_OR_PATH ) ; } return derive ( UriPart . MAYBE_VARIABLE_SCHEME ) ; } return this ; } | The context after printing a correctly - escaped dynamic value in this context . | 394 | 14 |
30,737 | static Context computeContextAfterAttributeDelimiter ( ElementType elType , AttributeType attrType , AttributeEndDelimiter delim , UriType uriType , int templateNestDepth ) { HtmlContext state ; JsFollowingSlash slash = JsFollowingSlash . NONE ; UriPart uriPart = UriPart . NONE ; switch ( attrType ) { case PLAIN_TEXT : state = HtmlContext . HTML_NORMAL_ATTR_VALUE ; break ; case SCRIPT : state = HtmlContext . JS ; // Start a JS block in a regex state since // /foo/.test(str) && doSideEffect(); // which starts with a regular expression literal is a valid and possibly useful program, // but there is no valid program which starts with a division operator. slash = JsFollowingSlash . REGEX ; break ; case STYLE : state = HtmlContext . CSS ; break ; case HTML : state = HtmlContext . HTML_HTML_ATTR_VALUE ; break ; case META_REFRESH_CONTENT : state = HtmlContext . HTML_META_REFRESH_CONTENT ; break ; case URI : state = HtmlContext . URI ; uriPart = UriPart . START ; break ; // NONE is not a valid AttributeType inside an attribute value. default : throw new AssertionError ( "Unexpected attribute type " + attrType ) ; } Preconditions . checkArgument ( ( uriType != UriType . NONE ) == ( attrType == AttributeType . URI ) , "uriType=%s but attrType=%s" , uriType , attrType ) ; return new Context ( state , elType , attrType , delim , slash , uriPart , uriType , HtmlHtmlAttributePosition . NONE , templateNestDepth , 0 ) ; } | Computes the context after an attribute delimiter is seen . | 410 | 12 |
30,738 | Optional < MsgEscapingStrategy > getMsgEscapingStrategy ( SoyNode node ) { switch ( state ) { case HTML_PCDATA : // In normal HTML PCDATA context, it makes sense to escape all of the print nodes, but not // escape the entire message. This allows Soy to support putting anchors and other small // bits of HTML in messages. return Optional . of ( new MsgEscapingStrategy ( this , ImmutableList . of ( ) ) ) ; case CSS_DQ_STRING : case CSS_SQ_STRING : case JS_DQ_STRING : case JS_SQ_STRING : case TEXT : case URI : if ( state == HtmlContext . URI && uriPart != UriPart . QUERY ) { // NOTE: Only support the query portion of URIs. return Optional . absent ( ) ; } // In other contexts like JS and CSS strings, it makes sense to treat the message's // placeholders as plain text, but escape the entire result of message evaluation. return Optional . of ( new MsgEscapingStrategy ( new Context ( HtmlContext . TEXT ) , getEscapingModes ( node , ImmutableList . of ( ) ) ) ) ; case HTML_RCDATA : case HTML_NORMAL_ATTR_VALUE : case HTML_COMMENT : // The weirdest case is HTML attributes. Ideally, we'd like to treat these as a text string // and escape when done. However, many messages have HTML entities such as » in them. // A good way around this is to escape the print nodes in the message, but normalize // (escape except for ampersands) the final message. // Also, content inside <title>, <textarea>, and HTML comments have a similar requirement, // where any entities in the messages are probably intended to be preserved. return Optional . of ( new MsgEscapingStrategy ( this , ImmutableList . of ( EscapingMode . NORMALIZE_HTML ) ) ) ; default : // Other contexts, primarily source code contexts, don't have a meaningful way to support // natural language text. return Optional . absent ( ) ; } } | Determines the strategy to escape Soy msg tags . | 460 | 11 |
30,739 | public boolean isCompatibleWith ( EscapingMode mode ) { // TODO: Come up with a compatibility matrix. if ( mode == EscapingMode . ESCAPE_JS_VALUE ) { // Don't introduce quotes inside a string. switch ( state ) { case JS_SQ_STRING : case JS_DQ_STRING : case CSS_SQ_STRING : case CSS_DQ_STRING : return false ; default : return true ; } } else if ( mode == EscapingMode . TEXT ) { // The TEXT directive may only be used in TEXT mode; in any other context, it would act as // autoescape-cancelling. return state == HtmlContext . TEXT ; } else if ( delimType == AttributeEndDelimiter . SPACE_OR_TAG_END ) { // Need ESCAPE_HTML_ATTRIBUTE_NOSPACE instead. if ( mode == EscapingMode . ESCAPE_HTML || mode == EscapingMode . ESCAPE_HTML_ATTRIBUTE || mode == EscapingMode . ESCAPE_HTML_RCDATA ) { return false ; } } return true ; } | True if the given escaping mode could make sense in this context . | 244 | 13 |
30,740 | public int packedBits ( ) { int bits = templateNestDepth ; bits = ( bits << N_URI_TYPE_BITS ) | uriType . ordinal ( ) ; bits = ( bits << N_URI_PART_BITS ) | uriPart . ordinal ( ) ; bits = ( bits << N_JS_SLASH_BITS ) | slashType . ordinal ( ) ; bits = ( bits << N_DELIM_BITS ) | delimType . ordinal ( ) ; bits = ( bits << N_ATTR_BITS ) | attrType . ordinal ( ) ; bits = ( bits << N_ELEMENT_BITS ) | elType . ordinal ( ) ; bits = ( bits << N_STATE_BITS ) | state . ordinal ( ) ; return bits ; } | An integer form that uniquely identifies this context . This form is not guaranteed to be stable across versions so do not use as a long - lived serialized form . | 181 | 32 |
30,741 | private static UriPart unionUriParts ( UriPart a , UriPart b ) { Preconditions . checkArgument ( a != b ) ; if ( a == UriPart . DANGEROUS_SCHEME || b == UriPart . DANGEROUS_SCHEME ) { // Dangerous schemes (like javascript:) are poison -- if either side is dangerous, the whole // thing is. return UriPart . DANGEROUS_SCHEME ; } else if ( a == UriPart . FRAGMENT || b == UriPart . FRAGMENT || a == UriPart . UNKNOWN || b == UriPart . UNKNOWN ) { // UNKNOWN means one part is in the #fragment and one is not. This is the case if one is // FRAGMENT and the other is not, or if one of the branches was UNKNOWN to begin with. return UriPart . UNKNOWN ; } else if ( ( a == UriPart . MAYBE_VARIABLE_SCHEME || b == UriPart . MAYBE_VARIABLE_SCHEME ) && a != UriPart . UNKNOWN_PRE_FRAGMENT && b != UriPart . UNKNOWN_PRE_FRAGMENT ) { // This is the case you might see on a URL that starts with a print statement, and one // branch has a slash or ampersand but the other doesn't. Re-entering // MAYBE_VARIABLE_SCHEME allows us to pretend that the last branch was just part of the // leading print statement, which leaves us in a relatively-unknown state, but no more // unknown had it just been completely opaque. // // Good Example 1: {$urlWithQuery}{if $a}&a={$a}{/if}{if $b}&b={$b}{/if} // In this example, the first "if" statement has two branches: // - "true": {$urlWithQuery}&a={$a} looks like a QUERY due to hueristics // - "false": {$urlWithQuery} only, which Soy doesn't know at compile-time to actually // have a query, and it remains in MAYBE_VARIABLE_SCHEME. // Instead of yielding UNKNOWN, this yields MAYBE_VARIABLE_SCHEME, which the second // {if $b} can safely deal with. // // Good Example 2: {$base}{if $a}/a{/if}{if $b}/b{/if} // In this, one branch transitions definitely into an authority or path, but the other // might not. However, we can remain in MAYBE_VARIABLE_SCHEME safely. return UriPart . MAYBE_VARIABLE_SCHEME ; } else { // The part is unknown, but we think it's before the fragment. In this case, it's clearly // ambiguous at compile-time that it's not clear what to do. Examples: // // /foo/{if $cond}?a={/if} // {$base}{if $cond}?a={$a}{else}/b{/if} // {if $cond}{$base}{else}/a{if $cond2}?b=1{/if}{/if} // // Unlike MAYBE_VARIABLE_SCHEME, we don't need to try to gracefully recover here, because // the template author can easily disambiguate this. return UriPart . UNKNOWN_PRE_FRAGMENT ; } } | Determines the correct URI part if two branches are joined . | 775 | 13 |
30,742 | @ VisibleForTesting static Context parse ( String text ) { Queue < String > parts = Lists . newLinkedList ( Arrays . asList ( text . split ( " " ) ) ) ; Context . Builder builder = HTML_PCDATA . toBuilder ( ) ; builder . withState ( HtmlContext . valueOf ( parts . remove ( ) ) ) ; if ( ! parts . isEmpty ( ) ) { try { builder . withElType ( ElementType . valueOf ( parts . element ( ) ) ) ; parts . remove ( ) ; } catch ( IllegalArgumentException ex ) { // OK } } if ( ! parts . isEmpty ( ) ) { try { builder . withAttrType ( AttributeType . valueOf ( parts . element ( ) ) ) ; parts . remove ( ) ; } catch ( IllegalArgumentException ex ) { // OK } } if ( ! parts . isEmpty ( ) ) { try { builder . withDelimType ( AttributeEndDelimiter . valueOf ( parts . element ( ) ) ) ; parts . remove ( ) ; } catch ( IllegalArgumentException ex ) { // OK } } if ( ! parts . isEmpty ( ) ) { try { builder . withSlashType ( JsFollowingSlash . valueOf ( parts . element ( ) ) ) ; parts . remove ( ) ; } catch ( IllegalArgumentException ex ) { // OK } } if ( ! parts . isEmpty ( ) ) { try { builder . withUriPart ( UriPart . valueOf ( parts . element ( ) ) ) ; parts . remove ( ) ; } catch ( IllegalArgumentException ex ) { // OK } } if ( ! parts . isEmpty ( ) ) { try { builder . withUriType ( UriType . valueOf ( parts . element ( ) ) ) ; parts . remove ( ) ; } catch ( IllegalArgumentException ex ) { // OK } } if ( ! parts . isEmpty ( ) ) { String part = parts . element ( ) ; String prefix = "templateNestDepth=" ; if ( part . startsWith ( prefix ) ) { try { builder . withTemplateNestDepth ( Integer . parseInt ( part . substring ( prefix . length ( ) ) ) ) ; parts . remove ( ) ; } catch ( NumberFormatException ex ) { // OK } } } if ( ! parts . isEmpty ( ) ) { String part = parts . element ( ) ; String prefix = "jsTemplateLiteralNestDepth=" ; if ( part . startsWith ( prefix ) ) { try { builder . withJsTemplateLiteralNestDepth ( Integer . parseInt ( part . substring ( prefix . length ( ) ) ) ) ; parts . remove ( ) ; } catch ( NumberFormatException ex ) { // OK } } } if ( ! parts . isEmpty ( ) ) { throw new IllegalArgumentException ( "Unable to parse context \"" + text + "\". Unparsed portion: " + parts ) ; } Context result = builder . build ( ) ; return result ; } | Parses a condensed string version of a context for use in tests . | 653 | 15 |
30,743 | public boolean isValidStartContextForContentKind ( SanitizedContentKind contentKind ) { if ( templateNestDepth != 0 ) { return false ; } switch ( contentKind ) { case ATTRIBUTES : // Allow HTML attribute names, regardless of the kind of attribute (e.g. plain text) // or immediately after an open tag. return state == HtmlContext . HTML_ATTRIBUTE_NAME || state == HtmlContext . HTML_TAG ; default : // NOTE: For URI's, we need to be picky that the context has no attribute type, since we // don't want to forget to escape ampersands. return this . equals ( getStartContextForContentKind ( contentKind ) ) ; } } | Determines whether a particular context is valid at the start of a block of a particular content kind . | 155 | 21 |
30,744 | public boolean isValidStartContextForContentKindLoose ( SanitizedContentKind contentKind ) { switch ( contentKind ) { case URI : // Allow contextual templates directly call URI templates, even if we technically need to // do HTML-escaping for correct output. Supported browsers recover gracefully when // ampersands are underescaped, as long as there are no nearby semicolons. However, this // special case is limited ONLY to transitional cases, where the caller is contextual and // the callee is strict. return state == HtmlContext . URI ; default : return isValidStartContextForContentKind ( contentKind ) ; } } | Determines whether a particular context is allowed for contextual to strict calls . | 133 | 15 |
30,745 | public SanitizedContentKind getMostAppropriateContentKind ( ) { SanitizedContentKind kind = STATE_TO_CONTENT_KIND . get ( state ) ; if ( kind != null && isValidStartContextForContentKindLoose ( kind ) ) { return kind ; } return SanitizedContentKind . TEXT ; } | Returns the most sensible content kind for a context . | 69 | 10 |
30,746 | public final boolean isValidEndContextForContentKind ( SanitizedContentKind contentKind ) { if ( templateNestDepth != 0 ) { return false ; } switch ( contentKind ) { case CSS : return state == HtmlContext . CSS && elType == ElementType . NONE ; case HTML : return state == HtmlContext . HTML_PCDATA && elType == ElementType . NONE ; case ATTRIBUTES : // Allow any html attribute context or html tag this. HTML_TAG is needed for constructs // like "checked" that don't require an attribute value. Explicitly disallow // HTML_NORMAL_ATTR_VALUE (e.g. foo={$x} without quotes) to help catch cases where // attributes aren't safely composable (e.g. foo={$x}checked would end up with one long // attribute value, whereas foo="{$x}"checked would be parsed as intended). return state == HtmlContext . HTML_ATTRIBUTE_NAME || state == HtmlContext . HTML_TAG ; case JS : // Just ensure the state is JS -- don't worry about whether a regex is coming or not. return state == HtmlContext . JS && elType == ElementType . NONE ; case URI : // Ensure that the URI content is non-empty and the URI type remains normal (which is // the assumed type of the URI content kind). return state == HtmlContext . URI && uriType == UriType . NORMAL && uriPart != UriPart . START ; case TEXT : return state == HtmlContext . TEXT ; case TRUSTED_RESOURCE_URI : // Ensure that the URI content is non-empty and the URI type remains normal (which is // the assumed type of the URI content kind). return state == HtmlContext . URI && uriType == UriType . TRUSTED_RESOURCE && uriPart != UriPart . START ; } throw new IllegalArgumentException ( "Specified content kind " + contentKind + " has no associated end context." ) ; } | Determines whether a particular context is valid for the end of a block of a particular content kind . | 434 | 21 |
30,747 | public final String getLikelyEndContextMismatchCause ( SanitizedContentKind contentKind ) { Preconditions . checkArgument ( ! isValidEndContextForContentKind ( contentKind ) ) ; if ( contentKind == SanitizedContentKind . ATTRIBUTES ) { // Special error message for ATTRIBUTES since it has some specific logic. return "an unterminated attribute value, or ending with an unquoted attribute" ; } switch ( state ) { case HTML_TAG_NAME : case HTML_TAG : case HTML_ATTRIBUTE_NAME : case HTML_NORMAL_ATTR_VALUE : return "an unterminated HTML tag or attribute" ; case CSS : return "an unclosed style block or attribute" ; case JS : case JS_LINE_COMMENT : // Line comments are terminated by end of input. return "an unclosed script block or attribute" ; case CSS_COMMENT : case HTML_COMMENT : case JS_BLOCK_COMMENT : return "an unterminated comment" ; case CSS_DQ_STRING : case CSS_SQ_STRING : case JS_DQ_STRING : case JS_SQ_STRING : return "an unterminated string literal" ; case URI : case CSS_URI : case CSS_DQ_URI : case CSS_SQ_URI : return "an unterminated or empty URI" ; case JS_REGEX : return "an unterminated regular expression" ; default : if ( templateNestDepth != 0 ) { return "an unterminated <template> element" ; } else { return "unknown to compiler" ; } } } | Returns a plausible human - readable description of a context mismatch ; | 357 | 12 |
30,748 | public void increaseIndent ( int numStops ) { indentLen += numStops * indentIncrementLen ; Preconditions . checkState ( 0 <= indentLen && indentLen <= MAX_INDENT_LEN ) ; indent = SPACES . substring ( 0 , indentLen ) ; } | Increases the indent by the given number of stops . | 64 | 10 |
30,749 | public IndentedLinesBuilder appendParts ( Object ... parts ) { for ( Object part : parts ) { sb . append ( part ) ; } return this ; } | Appends some parts to the current line . | 35 | 9 |
30,750 | static TemplateAliases createTemplateAliases ( SoyFileNode fileNode ) { Map < String , String > aliasMap = new HashMap <> ( ) ; Set < String > localTemplates = new HashSet <> ( ) ; int counter = 0 ; ImmutableList . Builder < TemplateNode > templates = ImmutableList . builder ( ) ; templates . addAll ( SoyTreeUtils . getAllNodesOfType ( fileNode , TemplateBasicNode . class ) ) . addAll ( SoyTreeUtils . getAllNodesOfType ( fileNode , TemplateElementNode . class ) ) ; // Go through templates first and just alias them to their local name. for ( TemplateNode templateNode : templates . build ( ) ) { String partialName = templateNode . getPartialTemplateName ( ) ; String fullyQualifiedName = templateNode . getTemplateName ( ) ; localTemplates . add ( fullyQualifiedName ) ; Preconditions . checkState ( partialName != null , "Aliasing not supported for V1 templates" ) ; // Need to start the alias with something that cannot be a part of a reserved // JavaScript identifier like 'function' or 'catch'. String alias = "$" + partialName . substring ( 1 ) ; aliasMap . put ( fullyQualifiedName , alias ) ; } // Go through all call sites looking for foreign template calls and create an alias for them. for ( CallBasicNode callBasicNode : SoyTreeUtils . getAllNodesOfType ( fileNode , CallBasicNode . class ) ) { String fullyQualifiedName = callBasicNode . getCalleeName ( ) ; // We could have either encountered the foreign fully qualified name before or it could belong // to a local template. if ( localTemplates . contains ( fullyQualifiedName ) || aliasMap . containsKey ( fullyQualifiedName ) ) { continue ; } String alias = TEMPLATE_ALIAS_PREFIX + ( ++ counter ) ; aliasMap . put ( fullyQualifiedName , alias ) ; } return new Aliases ( aliasMap ) ; } | Creates a mapping for assigning and looking up the variable alias for templates both within a file and referenced from external files . For local files the alias is just the local template s name . For external templates the alias is an identifier that is unique for that template . | 441 | 52 |
30,751 | void generateTableEntries ( CodeBuilder ga ) { for ( Variable var : allVariables ) { try { var . local . tableEntry ( ga ) ; } catch ( Throwable t ) { throw new RuntimeException ( "unable to write table entry for: " + var . local , t ) ; } } } | Write a local variable table entry for every registered variable . | 67 | 11 |
30,752 | void defineFields ( ClassVisitor writer ) { for ( Variable var : allVariables ) { var . maybeDefineField ( writer ) ; } if ( currentCalleeField != null ) { currentCalleeField . defineField ( writer ) ; } if ( currentRendereeField != null ) { currentRendereeField . defineField ( writer ) ; } if ( currentAppendable != null ) { currentAppendable . defineField ( writer ) ; } } | Defines all the fields necessary for the registered variables . | 103 | 11 |
30,753 | FieldRef getCurrentCalleeField ( ) { FieldRef local = currentCalleeField ; if ( local == null ) { local = currentCalleeField = FieldRef . createField ( owner , CURRENT_CALLEE_FIELD , CompiledTemplate . class ) ; } return local ; } | Returns the field that holds the current callee template . | 66 | 11 |
30,754 | FieldRef getCurrentRenderee ( ) { FieldRef local = currentRendereeField ; if ( local == null ) { local = currentRendereeField = FieldRef . createField ( owner , CURRENT_RENDEREE_FIELD , SoyValueProvider . class ) ; } return local ; } | Returns the field that holds the currently rendering SoyValueProvider . | 65 | 12 |
30,755 | FieldRef getCurrentAppendable ( ) { FieldRef local = currentAppendable ; if ( local == null ) { local = currentAppendable = FieldRef . createField ( owner , CURRENT_APPENDABLE_FIELD , LoggingAdvisingAppendable . class ) ; } return local ; } | Returns the field that holds the currently rendering LoggingAdvisingAppendable object that is used for streaming renders . | 67 | 23 |
30,756 | Variable getVariable ( String name ) { VarKey varKey = VarKey . create ( Kind . USER_DEFINED , name ) ; return getVariable ( varKey ) ; } | Looks up a user defined variable with the given name . The variable must have been created in a currently active scope . | 39 | 23 |
30,757 | Variable getVariable ( SyntheticVarName name ) { VarKey varKey = VarKey . create ( Kind . SYNTHETIC , name . name ( ) ) ; return getVariable ( varKey ) ; } | Looks up a synthetic variable with the given name . The variable must have been created in a currently active scope . | 45 | 22 |
30,758 | public SanitizedContent knownDirAttrSanitized ( Dir dir ) { Preconditions . checkNotNull ( dir ) ; if ( dir != contextDir ) { switch ( dir ) { case LTR : return LTR_DIR ; case RTL : return RTL_DIR ; case NEUTRAL : // fall out. } } return NEUTRAL_DIR ; } | Returns dir = \ ltr \ or dir = \ rtl \ depending on the given directionality if it is not NEUTRAL or the same as the context directionality . Otherwise returns . | 78 | 39 |
30,759 | @ VisibleForTesting static Dir estimateDirection ( String str , boolean isHtml ) { return BidiUtils . estimateDirection ( str , isHtml ) ; } | Estimates the directionality of a string using the best known general - purpose method i . e . using relative word counts . Dir . NEUTRAL return value indicates completely neutral input . | 38 | 37 |
30,760 | public static ValidatedConformanceConfig create ( ConformanceConfig config ) { ImmutableList . Builder < RuleWithWhitelists > rulesBuilder = new ImmutableList . Builder <> ( ) ; for ( Requirement requirement : config . getRequirementList ( ) ) { Preconditions . checkArgument ( ! requirement . getErrorMessage ( ) . isEmpty ( ) , "requirement missing error message" ) ; Preconditions . checkArgument ( requirement . getRequirementTypeCase ( ) != RequirementTypeCase . REQUIREMENTTYPE_NOT_SET , "requirement missing type" ) ; Rule < ? extends Node > rule = forRequirement ( requirement ) ; ImmutableList < String > whitelists = ImmutableList . copyOf ( requirement . getWhitelistList ( ) ) ; ImmutableList < String > onlyApplyToPaths = ImmutableList . copyOf ( requirement . getOnlyApplyToList ( ) ) ; rulesBuilder . add ( RuleWithWhitelists . create ( rule , whitelists , onlyApplyToPaths ) ) ; } return new ValidatedConformanceConfig ( rulesBuilder . build ( ) ) ; } | Creates a validated configuration object . | 245 | 7 |
30,761 | private static Rule < ? > createCustomRule ( String javaClass , SoyErrorKind error ) { Class < ? extends Rule < ? > > customRuleClass ; try { @ SuppressWarnings ( "unchecked" ) Class < ? extends Rule < ? > > asSubclass = ( Class < ? extends Rule < ? > > ) Class . forName ( javaClass ) . asSubclass ( Rule . class ) ; customRuleClass = asSubclass ; } catch ( ClassNotFoundException e ) { throw new IllegalArgumentException ( "custom rule class " + javaClass + " not found" , e ) ; } try { // It is ok for the constructor to be non-public as long as it is defined in this package // if it is non public and defined in another package, this will throw an // IllegalAccessException which seems about right. Constructor < ? extends Rule < ? > > ctor = customRuleClass . getDeclaredConstructor ( SoyErrorKind . class ) ; return ctor . newInstance ( error ) ; } catch ( ReflectiveOperationException e ) { throw new IllegalArgumentException ( "unable to construct custom rule class: " + javaClass + ": " + e . getMessage ( ) , e ) ; } } | Instantiates a custom conformance check from its fully - qualified class name specified in the conformance protobuf . | 267 | 24 |
30,762 | public void setUseGoogIsRtlForBidiGlobalDir ( boolean useGoogIsRtlForBidiGlobalDir ) { Preconditions . checkState ( ! useGoogIsRtlForBidiGlobalDir || shouldGenerateGoogMsgDefs , "Do not specify useGoogIsRtlForBidiGlobalDir without shouldGenerateGoogMsgDefs." ) ; Preconditions . checkState ( ! useGoogIsRtlForBidiGlobalDir || bidiGlobalDir == 0 , "Must not specify both bidiGlobalDir and useGoogIsRtlForBidiGlobalDir." ) ; this . useGoogIsRtlForBidiGlobalDir = useGoogIsRtlForBidiGlobalDir ; } | Sets the Javascript code snippet that will evaluate at template runtime to a boolean value indicating whether the bidi global direction is rtl . Can only be used when shouldGenerateGoogMsgDefs is true . | 163 | 43 |
30,763 | @ Override protected PyExpr visitPrimitiveNode ( PrimitiveNode node ) { // Note: ExprNode.toSourceString() technically returns a Soy expression. In the case of // primitives, the result is usually also the correct Python expression. return new PyExpr ( node . toSourceString ( ) , Integer . MAX_VALUE ) ; } | Implementations for primitives . | 75 | 7 |
30,764 | private PyExpr genPyExprUsingSoySyntax ( OperatorNode opNode ) { List < PyExpr > operandPyExprs = visitChildren ( opNode ) ; String newExpr = PyExprUtils . genExprWithNewToken ( opNode . getOperator ( ) , operandPyExprs , null ) ; return new PyExpr ( newExpr , PyExprUtils . pyPrecedenceForOperator ( opNode . getOperator ( ) ) ) ; } | Generates a Python expression for the given OperatorNode s subtree assuming that the Python expression for the operator uses the same syntax format as the Soy operator . | 113 | 31 |
30,765 | public static void ensureDirsExistInPath ( String path ) { if ( path == null || path . length ( ) == 0 ) { throw new AssertionError ( "ensureDirsExistInPath called with null or empty path." ) ; } String dirPath = ( path . charAt ( path . length ( ) - 1 ) == File . separatorChar ) ? path . substring ( 0 , path . length ( ) - 1 ) : ( new File ( path ) ) . getParent ( ) ; if ( dirPath == null || knownExistingDirs . contains ( dirPath ) ) { return ; // known to exist } else { ( new File ( dirPath ) ) . mkdirs ( ) ; knownExistingDirs . add ( dirPath ) ; } } | Ensures that the directories in the given path exist creating them if necessary . | 169 | 16 |
30,766 | public static String extractPartAfterLastDot ( String dottedIdent ) { int lastDotIndex = dottedIdent . lastIndexOf ( ' ' ) ; return ( lastDotIndex == - 1 ) ? dottedIdent : dottedIdent . substring ( lastDotIndex + 1 ) ; } | Gets the part after the last dot in a dotted identifier . If there are no dots returns the whole input string . | 61 | 24 |
30,767 | public final SoyTypeP toProto ( ) { SoyTypeP local = protoDual ; if ( local == null ) { SoyTypeP . Builder builder = SoyTypeP . newBuilder ( ) ; doToProto ( builder ) ; local = builder . build ( ) ; protoDual = local ; } return local ; } | The type represented in proto format . For template metadata protos . | 68 | 13 |
30,768 | public SourceLocation substringLocation ( int start , int end ) { checkElementIndex ( start , rawText . length ( ) , "start" ) ; checkArgument ( start < end ) ; checkArgument ( end <= rawText . length ( ) ) ; if ( offsets == null ) { return getSourceLocation ( ) ; } return new SourceLocation ( getSourceLocation ( ) . getFilePath ( ) , offsets . getPoint ( rawText , start ) , // source locations are inclusive, the end locations should point at the last character // in the string, whereas substring is usually specified exclusively, so subtract 1 to make // up the difference offsets . getPoint ( rawText , end - 1 ) ) ; } | Returns the source location of the given substring . | 150 | 10 |
30,769 | public void rewrite ( ImmutableList < SoyFileNode > sourceFiles , IdGenerator idGenerator , TemplateRegistry registry ) { // Inferences collects all the typing decisions we make and escaping modes we choose. Inferences inferences = new Inferences ( registry ) ; // TODO(lukes): having a separation of inference and rewriting was important when we did // template cloning and derivation. Now that that is deleted we could combine these into a // single pass over the tree and delete the Inferences class which may simplify things. for ( SoyFileNode file : sourceFiles ) { for ( TemplateNode templateNode : file . getChildren ( ) ) { try { // The author specifies the kind of SanitizedContent to produce, and thus the context in // which to escape. Context startContext = Context . getStartContextForContentKind ( MoreObjects . firstNonNull ( templateNode . getContentKind ( ) , SanitizedContentKind . HTML ) ) ; InferenceEngine . inferTemplateEndContext ( templateNode , startContext , inferences , errorReporter ) ; } catch ( SoyAutoescapeException e ) { reportError ( errorReporter , e ) ; } } } if ( errorReporter . hasErrors ( ) ) { return ; } // Now that we know we don't fail with exceptions, apply the changes to the given files. Rewriter rewriter = new Rewriter ( inferences , idGenerator , printDirectives ) ; for ( SoyFileNode file : sourceFiles ) { rewriter . rewrite ( file ) ; } } | Rewrites the given Soy files so that dynamic output is properly escaped according to the context in which it appears . | 325 | 22 |
30,770 | private void reportError ( ErrorReporter errorReporter , SoyAutoescapeException e ) { // First, get to the root cause of the exception, and assemble an error message indicating // the full call stack that led to the failure. String message = "- " + e . getOriginalMessage ( ) ; while ( e . getCause ( ) instanceof SoyAutoescapeException ) { e = ( SoyAutoescapeException ) e . getCause ( ) ; message += "\n- " + e . getMessage ( ) ; } errorReporter . report ( e . getSourceLocation ( ) , AUTOESCAPE_ERROR , message ) ; } | Reports an autoescape exception . | 137 | 7 |
30,771 | public void accumulateActiveEdges ( ImmutableList < ActiveEdge > activeEdges ) { for ( ActiveEdge accEdge : activeEdges ) { accEdge . getGraphNode ( ) . linkEdgeToNode ( accEdge . getActiveEdge ( ) , this ) ; } } | Links the all the given active edges to this node . | 59 | 11 |
30,772 | static SourceLocation createSrcLoc ( String filePath , Token first , Token ... rest ) { int beginLine = first . beginLine ; int beginColumn = first . beginColumn ; int endLine = first . endLine ; int endColumn = first . endColumn ; for ( Token next : rest ) { checkArgument ( startsLaterThan ( next , beginLine , beginColumn ) ) ; checkArgument ( endsLaterThan ( next , endLine , endColumn ) ) ; endLine = next . endLine ; endColumn = next . endColumn ; } // this special case happens for completely empty files. if ( beginLine == 0 && endLine == 0 && beginColumn == 0 && endColumn == 0 ) { return new SourceLocation ( filePath ) ; } return new SourceLocation ( filePath , beginLine , beginColumn , endLine , endColumn ) ; } | Returns a source location for the given tokens . | 184 | 9 |
30,773 | public ImmutableList < TemplateMetadata > getTemplates ( CallNode node ) { if ( node instanceof CallBasicNode ) { String calleeName = ( ( CallBasicNode ) node ) . getCalleeName ( ) ; TemplateMetadata template = basicTemplatesOrElementsMap . get ( calleeName ) ; return template == null ? ImmutableList . of ( ) : ImmutableList . of ( template ) ; } else { String calleeName = ( ( CallDelegateNode ) node ) . getDelCalleeName ( ) ; return delTemplateSelector . delTemplateNameToValues ( ) . get ( calleeName ) ; } } | Look up possible targets for a call . | 142 | 8 |
30,774 | public Optional < SanitizedContentKind > getCallContentKind ( CallNode node ) { ImmutableList < TemplateMetadata > templateNodes = getTemplates ( node ) ; // For per-file compilation, we may not have any of the delegate templates in the compilation // unit. if ( ! templateNodes . isEmpty ( ) ) { return Optional . fromNullable ( templateNodes . get ( 0 ) . getContentKind ( ) ) ; } // The template node may be null if the template is being compiled in isolation. return Optional . absent ( ) ; } | Gets the content kind that a call results in . If used with delegate calls the delegate templates must use strict autoescaping . This relies on the fact that all delegate calls must have the same kind when using strict autoescaping . This is enforced by CheckDelegatesPass . | 120 | 58 |
30,775 | public static TemplateMetadata fromTemplate ( TemplateNode template ) { TemplateMetadata . Builder builder = builder ( ) . setTemplateName ( template . getTemplateName ( ) ) . setSourceLocation ( template . getSourceLocation ( ) ) . setSoyFileKind ( SoyFileKind . SRC ) . setContentKind ( template . getContentKind ( ) ) . setStrictHtml ( template . isStrictHtml ( ) ) . setDelPackageName ( template . getDelPackageName ( ) ) . setVisibility ( template . getVisibility ( ) ) . setParameters ( Parameter . directParametersFromTemplate ( template ) ) . setDataAllCallSituations ( DataAllCallSituation . fromTemplate ( template ) ) ; switch ( template . getKind ( ) ) { case TEMPLATE_BASIC_NODE : builder . setTemplateKind ( Kind . BASIC ) ; break ; case TEMPLATE_DELEGATE_NODE : builder . setTemplateKind ( Kind . DELTEMPLATE ) ; TemplateDelegateNode deltemplate = ( TemplateDelegateNode ) template ; builder . setDelTemplateName ( deltemplate . getDelTemplateName ( ) ) ; builder . setDelTemplateVariant ( deltemplate . getDelTemplateVariant ( ) ) ; break ; case TEMPLATE_ELEMENT_NODE : builder . setTemplateKind ( Kind . ELEMENT ) ; break ; default : throw new AssertionError ( "unexpected template kind: " + template . getKind ( ) ) ; } return builder . build ( ) ; } | Builds a Template from a parsed TemplateNode . | 339 | 10 |
30,776 | @ Override protected Expression maybeWrapContent ( CodeChunk . Generator generator , CallParamContentNode node , Expression content ) { SanitizedContentKind kind = node . getContentKind ( ) ; if ( kind == SanitizedContentKind . HTML || kind == SanitizedContentKind . ATTRIBUTES ) { return content ; } return super . maybeWrapContent ( generator , node , content ) ; } | Never wrap contents as SanitizedContent if HTML or ATTRIBUTES . | 86 | 16 |
30,777 | public CompiledTemplate . Factory getTemplateFactory ( String name ) { CompiledTemplate . Factory factory = getTemplateData ( name ) . factory ; if ( factory == null ) { throw new IllegalArgumentException ( "cannot get a factory for the private template: " + name ) ; } return factory ; } | Returns a factory for the given fully qualified template name . | 65 | 11 |
30,778 | public ImmutableSortedSet < String > getTransitiveIjParamsForTemplate ( String templateName ) { TemplateData templateData = getTemplateData ( templateName ) ; ImmutableSortedSet < String > transitiveIjParams = templateData . transitiveIjParams ; // racy-lazy init pattern. We may calculate this more than once, but that is fine because each // time should calculate the same value. if ( transitiveIjParams != null ) { // early return, we already calculated this. return transitiveIjParams ; } Set < TemplateData > all = new HashSet <> ( ) ; collectTransitiveCallees ( templateData , all ) ; ImmutableSortedSet . Builder < String > ijs = ImmutableSortedSet . naturalOrder ( ) ; for ( TemplateData callee : all ) { ijs . addAll ( callee . injectedParams ) ; } transitiveIjParams = ijs . build ( ) ; // save the results templateData . transitiveIjParams = transitiveIjParams ; return transitiveIjParams ; } | Returns the transitive closure of all the injected params that might be used by this template . | 244 | 18 |
30,779 | private String generateOptionalSafeTagsArg ( List < ? extends TargetExpr > args ) { String optionalSafeTagsArg = "" ; if ( ! args . isEmpty ( ) ) { // TODO(msamuel): Instead of parsing generated JS, we should have a CheckArgumentsPass that // allows directives and functions to examine their input expressions prior to compilation and // relay the input file and line number to the template author along with an error message. Iterable < String > optionalSafeTagExprs = Iterables . transform ( args , TargetExpr :: getText ) ; // Verify that all exprs are single-quoted valid OptionalSafeTags. for ( String singleQuoted : optionalSafeTagExprs ) { if ( singleQuoted . length ( ) < 2 || singleQuoted . charAt ( 0 ) != ' ' || singleQuoted . charAt ( singleQuoted . length ( ) - 1 ) != ' ' ) { throw new IllegalArgumentException ( String . format ( "The cleanHtml directive expects arguments to be tag name string " + "literals, such as 'span'. Encountered: %s" , singleQuoted ) ) ; } String tagName = singleQuoted . substring ( 1 , singleQuoted . length ( ) - 1 ) ; OptionalSafeTag . fromTagName ( tagName ) ; // throws if invalid } optionalSafeTagsArg = ", [" + ARG_JOINER . join ( optionalSafeTagExprs ) + "]" ; } return optionalSafeTagsArg ; } | Converts a list of TargetExpr s into a list of safe tags as an argument for the supported backends . This will iterate over the expressions ensure they re valid safe tags and convert them into an array of Strings . | 325 | 47 |
30,780 | private Optional < Expression > asRawTextOnly ( String name , RenderUnitNode renderUnit ) { StringBuilder builder = null ; List < SoyNode > children = new ArrayList <> ( renderUnit . getChildren ( ) ) ; for ( int i = 0 ; i < children . size ( ) ; i ++ ) { SoyNode child = children . get ( i ) ; if ( child instanceof MsgHtmlTagNode ) { // by the time MsgHtmlTagNodes hit the code generator the HtmlTagNode instances they wrap // have been desugared into RawTextNodes (and other things). children . addAll ( i + 1 , ( ( MsgHtmlTagNode ) child ) . getChildren ( ) ) ; continue ; } if ( child instanceof RawTextNode ) { if ( builder == null ) { builder = new StringBuilder ( ) ; } builder . append ( ( ( RawTextNode ) child ) . getRawText ( ) ) ; } else { return Optional . absent ( ) ; } } SanitizedContentKind kind = renderUnit . getContentKind ( ) ; Expression value = constant ( builder == null ? "" : builder . toString ( ) , parentVariables ) ; if ( kind == null ) { value = MethodRef . STRING_DATA_FOR_VALUE . invoke ( value ) ; } else { value = MethodRef . ORDAIN_AS_SAFE . invoke ( value , constantSanitizedContentKindAsContentKind ( kind ) ) ; } FieldRef staticField = parentVariables . addStaticField ( name , value ) ; return Optional . of ( staticField . accessor ( ) ) ; } | Returns an SoyValueProvider expression for the given RenderUnitNode if it is composed of only raw text . | 350 | 21 |
30,781 | public final void gen ( CodeBuilder adapter ) { boolean shouldClearIsGeneratingBit = false ; if ( Flags . DEBUG && ! isGenerating . get ( ) ) { isGenerating . set ( true ) ; shouldClearIsGeneratingBit = true ; } try { if ( location . isKnown ( ) ) { // These add entries to the line number tables that are associated with the current method. // The line number table is just a mapping of bytecode offset (aka 'pc') to line number, // http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.12 // It is used by the JVM to add source data to stack traces and by debuggers to highlight // source files. Label start = new Label ( ) ; adapter . mark ( start ) ; adapter . visitLineNumber ( location . getBeginLine ( ) , start ) ; } doGen ( adapter ) ; if ( location . isKnown ( ) ) { Label end = new Label ( ) ; adapter . mark ( end ) ; adapter . visitLineNumber ( location . getEndLine ( ) , end ) ; } } finally { if ( shouldClearIsGeneratingBit ) { isGenerating . set ( false ) ; } } } | Writes the bytecode to the adapter . | 281 | 9 |
30,782 | private void setCompileTimeGlobalsInternal ( ImmutableMap < String , PrimitiveData > compileTimeGlobalsMap ) { Preconditions . checkState ( compileTimeGlobals == null , "Compile-time globals already set." ) ; compileTimeGlobals = compileTimeGlobalsMap ; } | Sets the map from compile - time global name to value using Soy primitive types . | 70 | 17 |
30,783 | public SoyGeneralOptions setCompileTimeGlobals ( File compileTimeGlobalsFile ) throws IOException { setCompileTimeGlobalsInternal ( SoyUtils . parseCompileTimeGlobals ( Files . asCharSource ( compileTimeGlobalsFile , UTF_8 ) ) ) ; return this ; } | Sets the file containing compile - time globals . | 69 | 11 |
30,784 | public SoyGeneralOptions setCompileTimeGlobals ( URL compileTimeGlobalsResource ) throws IOException { setCompileTimeGlobalsInternal ( SoyUtils . parseCompileTimeGlobals ( Resources . asCharSource ( compileTimeGlobalsResource , UTF_8 ) ) ) ; return this ; } | Sets the resource file containing compile - time globals . | 69 | 12 |
30,785 | @ Nullable public String getStaticContent ( ) { if ( ! hasValue ( ) ) { return null ; } HtmlAttributeValueNode attrValue = ( HtmlAttributeValueNode ) getChild ( 1 ) ; if ( attrValue . numChildren ( ) == 0 ) { return "" ; } if ( attrValue . numChildren ( ) > 1 ) { return null ; } StandaloneNode attrValueNode = attrValue . getChild ( 0 ) ; if ( ! ( attrValueNode instanceof RawTextNode ) ) { return null ; } return ( ( RawTextNode ) attrValueNode ) . getRawText ( ) ; } | Returns the static value if one exists or null otherwise . | 140 | 11 |
30,786 | public static BidiGlobalDir decodeBidiGlobalDirFromJsOptions ( int bidiGlobalDir , boolean useGoogIsRtlForBidiGlobalDir ) { if ( bidiGlobalDir == 0 ) { if ( ! useGoogIsRtlForBidiGlobalDir ) { return null ; } return BidiGlobalDir . forIsRtlCodeSnippet ( GOOG_IS_RTL_CODE_SNIPPET , GOOG_IS_RTL_CODE_SNIPPET_NAMESPACE , SoyBackendKind . JS_SRC ) ; } Preconditions . checkState ( ! useGoogIsRtlForBidiGlobalDir , "Must not specify both bidiGlobalDir and bidiGlobalDirIsRtlCodeSnippet." ) ; Preconditions . checkArgument ( bidiGlobalDir == 1 || bidiGlobalDir == - 1 , "If specified, bidiGlobalDir must be 1 for LTR or -1 for RTL." ) ; return BidiGlobalDir . forStaticIsRtl ( bidiGlobalDir < 0 ) ; } | Decodes the bidi global directionality from the usual command line options used to specify it . Checks that at most one of the options was specified . | 240 | 30 |
30,787 | public static BidiGlobalDir decodeBidiGlobalDirFromPyOptions ( String bidiIsRtlFn ) { if ( bidiIsRtlFn == null || bidiIsRtlFn . isEmpty ( ) ) { return null ; } int dotIndex = bidiIsRtlFn . lastIndexOf ( ' ' ) ; Preconditions . checkArgument ( dotIndex > 0 && dotIndex < bidiIsRtlFn . length ( ) - 1 , "If specified a bidiIsRtlFn must include the module path to allow for proper importing." ) ; // When importing the module, we'll using the constant name to avoid potential conflicts. String fnName = bidiIsRtlFn . substring ( dotIndex + 1 ) + "()" ; return BidiGlobalDir . forIsRtlCodeSnippet ( IS_RTL_MODULE_ALIAS + ' ' + fnName , null , SoyBackendKind . PYTHON_SRC ) ; } | Decodes bidi global directionality from the Python bidiIsRtlFn command line option . | 220 | 21 |
30,788 | @ Override public void beforeBlock ( ) { if ( count > 0 ) { try { flush ( ) ; } catch ( IOException e ) { logger . log ( Level . SEVERE , "Flush from soy failed" , e ) ; } } } | Soy is about to block on a future . Flush the output stream if there is anything to flush so we use the time we are blocking to transfer as many bytes as possible . | 55 | 37 |
30,789 | public void updateNames ( List < String > escapeMapNames , List < String > matcherNames , List < String > filterNames ) { // Store the names for this directive for use in building the helper function. escapesName = escapeMapVar >= 0 ? escapeMapNames . get ( escapeMapVar ) : null ; matcherName = matcherVar >= 0 ? matcherNames . get ( matcherVar ) : null ; filterName = filterVar >= 0 ? filterNames . get ( filterVar ) : null ; } | Update the escaper matcher and filter names based on the supplied lists and indices . | 109 | 17 |
30,790 | public static SanitizedContent emptyString ( ContentKind kind ) { if ( kind == ContentKind . TEXT ) { return UnsanitizedString . create ( "" ) ; } return SanitizedContent . create ( "" , kind , Dir . NEUTRAL ) ; // Empty string is neutral. } | Creates an empty string constant . | 60 | 7 |
30,791 | public static SanitizedContent fromResource ( Class < ? > contextClass , String resourceName , Charset charset , ContentKind kind ) throws IOException { pretendValidateResource ( resourceName , kind ) ; return SanitizedContent . create ( Resources . toString ( Resources . getResource ( contextClass , resourceName ) , charset ) , kind , // Text resources are usually localized, so one might think that the locale direction should // be assumed for them. We do not do that because: // - We do not know the locale direction here. // - Some messages do not get translated. // - This method currently can't be used for text resources (see pretendValidateResource()). kind . getDefaultDir ( ) ) ; } | Loads assumed - safe content from a Java resource . | 153 | 11 |
30,792 | public static SanitizedContent constantUri ( @ CompileTimeConstant final String constant ) { return fromConstant ( constant , ContentKind . URI , Dir . LTR ) ; } | Wraps an assumed - safe URI constant . | 39 | 9 |
30,793 | public static SanitizedContent constantHtml ( @ CompileTimeConstant final String constant ) { return fromConstant ( constant , ContentKind . HTML , null ) ; } | Wraps an assumed - safe constant string that specifies a safe balanced document fragment . | 36 | 16 |
30,794 | public static SanitizedContent constantAttributes ( @ CompileTimeConstant final String constant ) { return fromConstant ( constant , ContentKind . ATTRIBUTES , Dir . LTR ) ; } | Wraps an assumed - safe constant string that specifies an attribute . | 42 | 13 |
30,795 | public static SanitizedContent constantCss ( @ CompileTimeConstant final String constant ) { return fromConstant ( constant , ContentKind . CSS , Dir . LTR ) ; } | Wraps an assumed - safe CSS constant . | 39 | 9 |
30,796 | public static SanitizedContent constantJs ( @ CompileTimeConstant final String constant ) { return fromConstant ( constant , ContentKind . JS , Dir . LTR ) ; } | Wraps an assumed - safe JS constant . | 38 | 9 |
30,797 | public static SanitizedContent constantTrustedResourceUri ( @ CompileTimeConstant final String constant ) { return fromConstant ( constant , ContentKind . TRUSTED_RESOURCE_URI , Dir . LTR ) ; } | Wraps an assumed - safe trusted_resource_uri constant . | 49 | 13 |
30,798 | public static SanitizedContent numberJs ( final long number ) { return SanitizedContent . create ( String . valueOf ( number ) , ContentKind . JS ) ; } | Creates JS from a number . | 35 | 7 |
30,799 | @ VisibleForTesting static void pretendValidateResource ( String resourceName , ContentKind kind ) { int index = resourceName . lastIndexOf ( ' ' ) ; Preconditions . checkArgument ( index >= 0 , "Currently, we only validate resources with explicit extensions." ) ; String fileExtension = resourceName . substring ( index + 1 ) . toLowerCase ( ) ; switch ( kind ) { case JS : Preconditions . checkArgument ( fileExtension . equals ( "js" ) ) ; break ; case HTML : Preconditions . checkArgument ( SAFE_HTML_FILE_EXTENSIONS . contains ( fileExtension ) ) ; break ; case CSS : Preconditions . checkArgument ( fileExtension . equals ( "css" ) ) ; break ; default : throw new IllegalArgumentException ( "Don't know how to validate resources of kind " + kind ) ; } } | Very basic but strict validation that the resource s extension matches the content kind . | 195 | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.