code stringlengths 73 34.1k | label stringclasses 1
value |
|---|---|
public static SanitizedContent serializeElement(JsonElement element) {
// NOTE: Because JsonElement doesn't have any particular mechanism preventing random classes
// from impersonating it, this low-tech check prevents at least obvious misuse.
Preconditions.checkArgument(
element instanceof JsonArra... | java |
public boolean isJustBefore(SourceLocation that) {
if (!this.filePath.equals(that.filePath)) {
return false;
}
return this.getEndLine() == that.getBeginLine()
&& this.getEndColumn() + 1 == that.getBeginColumn();
} | java |
public final String getStatementsForInsertingIntoForeignCodeAtIndent(int startingIndent) {
String code = getCode(startingIndent);
return code.endsWith("\n") ? code : code + "\n";
} | java |
public void addNode(HtmlMatcherGraphNode node) {
checkNotNull(node);
if (graphCursor.isPresent()) {
graphCursor.get().linkActiveEdgeToNode(node);
}
setGraphCursorNode(node);
} | java |
public static void main(String[] args) {
// Compile the template.
SoyFileSet sfs = SoyFileSet.builder().add(Resources.getResource("simple.soy")).build();
SoyTofu tofu = sfs.compileToTofu();
// Example 1.
writeExampleHeader();
System.out.println(tofu.newRenderer("soy.examples.simple.helloWorld"... | java |
private DelTemplateKey resolveVariantExpression() {
if (delTemplateVariantExpr == null) {
delTemplateKey = DelTemplateKey.create(delTemplateName, "");
return delTemplateKey;
}
ExprNode exprNode = delTemplateVariantExpr.getRoot();
if (exprNode instanceof GlobalNode) {
GlobalNode globalN... | java |
public String toSourceString() {
return "{namespace "
+ namespace.identifier()
+ (attrs.isEmpty() ? "" : " " + Joiner.on(' ').join(attrs))
+ "}\n";
} | java |
public static String toJsUnpackFunction(Descriptor protoDescriptor) {
return Preconditions.checkNotNull(PROTO_TO_JS_UNPACK_FN.get(protoDescriptor.getFullName()));
} | java |
@Nullable
private static String getFullTagText(HtmlTagNode openTagNode) {
class Visitor implements NodeVisitor<Node, VisitDirective> {
boolean isConstantContent = true;
@Override
public VisitDirective exec(Node node) {
if (node instanceof RawTextNode
|| node instanceof HtmlA... | java |
public static JsExpr genJsExprUsingSoySyntax(Operator op, List<JsExpr> operandJsExprs) {
List<Expression> operands =
Lists.transform(operandJsExprs, input -> fromExpr(input, ImmutableList.<GoogRequire>of()));
return Expression.operation(op, operands).assertExpr();
} | java |
public static Type protoType(Descriptor descriptor) {
return Type.getType('L' + JavaQualifiedNames.getClassName(descriptor).replace('.', '/') + ';');
} | java |
public static List<SoyValueProvider> concatLists(List<SoyList> args) {
ImmutableList.Builder<SoyValueProvider> flattened = ImmutableList.builder();
for (SoyList soyList : args) {
flattened.addAll(soyList.asJavaList());
}
return flattened.build();
} | java |
public static String join(SoyList list, String separator) {
List<String> stringList = new ArrayList<>();
for (SoyValue value : list.asResolvedJavaList()) {
stringList.add(value.coerceToString());
}
return Joiner.on(separator).join(stringList);
} | java |
public static List<SoyValue> keys(SoyValue sv) {
SoyLegacyObjectMap map = (SoyLegacyObjectMap) sv;
List<SoyValue> list = new ArrayList<>(map.getItemCnt());
Iterables.addAll(list, map.getItemKeys());
return list;
} | java |
public static NumberData max(SoyValue arg0, SoyValue arg1) {
if (arg0 instanceof IntegerData && arg1 instanceof IntegerData) {
return IntegerData.forValue(Math.max(arg0.longValue(), arg1.longValue()));
} else {
return FloatData.forValue(Math.max(arg0.numberValue(), arg1.numberValue()));
}
} | java |
public static long round(SoyValue value) {
if (value instanceof IntegerData) {
return value.longValue();
} else {
return Math.round(value.numberValue());
}
} | java |
public void setParamsToRuntimeCheck(
ImmutableMap<String, Predicate<String>> paramsToRuntimeCheck) {
checkState(this.paramsToRuntimeCheckByDelegate == null);
this.paramsToRuntimeCheckByDelegate = checkNotNull(paramsToRuntimeCheck);
} | java |
static BasicExpressionCompiler createBasicCompiler(
TemplateParameterLookup parameters,
TemplateVariableManager varManager,
ErrorReporter reporter,
SoyTypeRegistry registry) {
return new BasicExpressionCompiler(parameters, varManager, reporter, registry);
} | java |
SoyExpression compile(ExprNode node, Label reattachPoint) {
return asBasicCompiler(reattachPoint).compile(node);
} | java |
Optional<SoyExpression> compileWithNoDetaches(ExprNode node) {
checkNotNull(node);
if (RequiresDetachVisitor.INSTANCE.exec(node)) {
return Optional.absent();
}
Supplier<ExpressionDetacher> throwingSupplier =
() -> {
throw new AssertionError();
};
return Optional.of(
... | java |
@Override
protected void visitPrintNode(PrintNode node) {
TranslateToPyExprVisitor translator =
new TranslateToPyExprVisitor(localVarExprs, pluginValueFactory, errorReporter);
PyExpr pyExpr = translator.exec(node.getExpr());
// Process directives.
for (PrintDirectiveNode directiveNode : node... | java |
@Override
protected void visitIfNode(IfNode node) {
// Create another instance of this visitor for generating Python expressions from children.
GenPyExprsVisitor genPyExprsVisitor =
genPyExprsVisitorFactory.create(localVarExprs, errorReporter);
TranslateToPyExprVisitor translator =
new Tra... | java |
@Nullable
public HtmlAttributeNode getDirectAttributeNamed(String attrName) {
// the child at index 0 is the tag name
for (int i = 1; i < numChildren(); i++) {
StandaloneNode child = getChild(i);
if (child instanceof HtmlAttributeNode) {
HtmlAttributeNode attr = (HtmlAttributeNode) child;
... | java |
private SoyList newListFromIterable(Iterable<?> items) {
// Create a list backed by a Java list which has eagerly converted each value into a lazy
// value provider. Specifically, the list iteration is done eagerly so that the lazy value
// provider can cache its value.
ImmutableList.Builder<SoyValuePro... | java |
public static MsgPartsAndIds buildMsgPartsAndComputeMsgIdForDualFormat(MsgNode msgNode) {
if (msgNode.isPlrselMsg()) {
MsgPartsAndIds mpai = buildMsgPartsAndComputeMsgIds(msgNode, true);
return new MsgPartsAndIds(mpai.parts, mpai.idUsingBracedPhs, -1L);
} else {
return buildMsgPartsAndCompute... | java |
private static long computeMsgId(MsgNode msgNode) {
return SoyMsgIdComputer.computeMsgId(
buildMsgParts(msgNode), msgNode.getMeaning(), msgNode.getContentType());
} | java |
private static long computeMsgIdUsingBracedPhs(MsgNode msgNode) {
return SoyMsgIdComputer.computeMsgIdUsingBracedPhs(
buildMsgParts(msgNode), msgNode.getMeaning(), msgNode.getContentType());
} | java |
private static ImmutableList<SoyMsgPart> buildMsgPartsForChildren(
MsgBlockNode parent, MsgNode msgNode) {
ImmutableList.Builder<SoyMsgPart> msgParts = ImmutableList.builder();
doBuildMsgPartsForChildren(parent, msgNode, msgParts);
return msgParts.build();
} | java |
private static SoyMsgPluralPart buildMsgPartForPlural(
MsgPluralNode msgPluralNode, MsgNode msgNode) {
// This is the list of the cases.
ImmutableList.Builder<SoyMsgPart.Case<SoyMsgPluralCaseSpec>> pluralCases =
ImmutableList.builder();
for (CaseOrDefaultNode child : msgPluralNode.getChildre... | java |
private static SoyMsgSelectPart buildMsgPartForSelect(
MsgSelectNode msgSelectNode, MsgNode msgNode) {
// This is the list of the cases.
ImmutableList.Builder<SoyMsgPart.Case<String>> selectCases = ImmutableList.builder();
for (CaseOrDefaultNode child : msgSelectNode.getChildren()) {
Immutable... | java |
public Expression gen(
CallNode callNode,
TemplateAliases templateAliases,
TranslationContext translationContext,
ErrorReporter errorReporter,
TranslateExprNodeVisitor exprTranslator) {
// Build the JS CodeChunk for the callee's name.
Expression callee = genCallee(callNode, templa... | java |
public Expression genObjToPass(
CallNode callNode,
TemplateAliases templateAliases,
TranslationContext translationContext,
ErrorReporter errorReporter,
TranslateExprNodeVisitor exprTranslator) {
// ------ Generate the expression for the original data to pass ------
Expression data... | java |
protected Expression maybeWrapContent(
CodeChunk.Generator generator, CallParamContentNode node, Expression content) {
if (node.getContentKind() == null) {
return content;
}
// Use the internal blocks wrapper, to maintain falsiness of empty string
return sanitizedContentOrdainerFunctionForI... | java |
@Nullable
public SoyType getType(String typeName) {
SoyType result = BUILTIN_TYPES.get(typeName);
if (result != null) {
return result;
}
synchronized (lock) {
result = protoTypeCache.get(typeName);
if (result == null) {
GenericDescriptor descriptor = descriptors.get(typeName)... | java |
public String findTypeWithMatchingNamespace(String prefix) {
prefix = prefix + ".";
// This must be sorted so that errors are deterministic, or we'll break integration tests.
for (String name : getAllSortedTypeNames()) {
if (name.startsWith(prefix)) {
return name;
}
}
return null... | java |
public Iterable<String> getAllSortedTypeNames() {
synchronized (lock) {
if (lazyAllSortedTypeNames == null) {
lazyAllSortedTypeNames =
Stream.concat(BUILTIN_TYPES.keySet().stream(), descriptors.keySet().stream())
.sorted()
.collect(toImmutableList());
... | java |
public SoyType getOrCreateUnionType(Collection<SoyType> members) {
SoyType type = UnionType.of(members);
if (type.getKind() == SoyType.Kind.UNION) {
type = unionTypes.intern((UnionType) type);
}
return type;
} | java |
public static SoyMsgRawTextPart of(String rawText) {
int utf8Length = Utf8.encodedLength(rawText);
// Determine whether UTF8 or UTF16 uses less memory, and choose between one of the two internal
// implementations. char[] is preferred if the sizes are equal because it is faster to turn
// back into a S... | java |
public boolean isPure() {
if (soyFunction instanceof BuiltinFunction) {
return ((BuiltinFunction) soyFunction).isPure();
}
return soyFunction.getClass().isAnnotationPresent(SoyPureFunction.class);
} | java |
void addToOutputVar(PyExpr pyExpr) {
boolean isList = pyExpr instanceof PyListExpr;
if (isList && !getOutputVarIsInited()) {
appendLine(getOutputVarName(), " = ", pyExpr.getText());
} else {
initOutputVarIfNecessary();
String function = isList ? ".extend(" : ".append(";
appendLine(ge... | java |
PyStringExpr getOutputAsString() {
Preconditions.checkState(getOutputVarName() != null);
initOutputVarIfNecessary();
return new PyListExpr(getOutputVarName(), Integer.MAX_VALUE).toPyString();
} | java |
@Nullable
public List<ExprRootNode> getAndRemoveGenderExprs() {
List<ExprRootNode> genderExprs = this.genderExprs;
this.genderExprs = null;
return genderExprs;
} | java |
public static ErrorReporter create(Map<String, SoyFileSupplier> filePathsToSuppliers) {
return new ErrorReporterImpl(ImmutableMap.copyOf(filePathsToSuppliers));
} | java |
public static boolean equal(SoyValue operand0, SoyValue operand1) {
// Treat the case where either is a string specially.
// TODO(gboyer): This should probably handle SanitizedContent == SanitizedContent, even though
// Javascript doesn't handle that case properly. http://b/21461181
if (operand0 instanc... | java |
public Expression reference() {
if (chunk() instanceof VariableDeclaration) {
return id(((VariableDeclaration) chunk()).varName(), ImmutableSet.of(this));
} else {
return dottedIdWithRequires(symbol(), ImmutableSet.of(this));
}
} | java |
public GoogRequire merge(GoogRequire other) {
checkArgument(other.symbol().equals(symbol()));
if (other.equals(this)) {
return this;
}
// if symbols are equal and the references are, then they must differ only by requireType or not
// prefer the non requireType symbol
if ((other.chunk() in... | java |
private Expression incrementKeyForTemplate(TemplateNode template) {
Holder<Integer> keyCounter = keyCounterStack.peek();
return JsRuntime.XID.call(
Expression.stringLiteral(template.getTemplateName() + "-" + keyCounter.value++));
} | java |
public void runWholeFilesetPasses(SoyFileSetNode soyTree, TemplateRegistry templateRegistry) {
ImmutableList<SoyFileNode> sourceFiles = ImmutableList.copyOf(soyTree.getChildren());
IdGenerator idGenerator = soyTree.getNodeIdGenerator();
for (CompilerFileSetPass pass : crossTemplateCheckingPasses) {
Co... | java |
protected void appendHeaderVarDecl(
ImmutableList<? extends TemplateHeaderVarDefn> headerVars, StringBuilder sb) {
for (TemplateHeaderVarDefn headerVar : headerVars) {
sb.append(" {").append(getDeclName(headerVar));
if (!headerVar.isRequired()) {
sb.append("?");
}
sb.append("... | java |
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.
... | java |
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();
... | java |
@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.
S... | java |
protected void writeStringLiteral(String value, StringBuilder out) {
out.append('\'').append(escapeOutputString(value)).append('\'');
} | java |
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('\... | java |
public static Expression extensionField(FieldDescriptor desc) {
String jsExtensionImport = ProtoUtils.getJsExtensionImport(desc);
String jsExtensionName = ProtoUtils.getJsExtensionName(desc);
return symbolWithNamespace(jsExtensionImport, jsExtensionName);
} | java |
public static Expression protoToSanitizedContentConverterFunction(Descriptor messageType) {
return GoogRequire.create(NodeContentKinds.toJsUnpackFunction(messageType)).reference();
} | java |
public static Expression protoConstructor(SoyProtoType type) {
return GoogRequire.create(type.getNameForBackend(SoyBackendKind.JS_SRC)).reference();
} | java |
public static Expression sanitizedContentType(SanitizedContentKind kind) {
return GoogRequire.create(NodeContentKinds.toJsSanitizedContentCtorName(kind)).reference();
} | java |
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.symbo... | java |
private boolean areChildrenComputableAsJsExprs(ParentSoyNode<?> node) {
for (SoyNode child : node.getChildren()) {
if (canSkipChild(child)) {
continue;
}
if (!visit(child)) {
return false;
}
}
return true;
} | java |
private ParseResult parseWithVersions() throws IOException {
List<TemplateMetadata> templateMetadatas = new ArrayList<>();
for (CompilationUnitAndKind unit : compilationUnits()) {
templateMetadatas.addAll(
TemplateMetadataSerializer.templatesFromCompilationUnit(
unit.compilationUni... | java |
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... | java |
public TypeInfo registerInnerClass(String simpleName, int accessModifiers) {
classNames.claimName(simpleName);
TypeInfo innerClass = outer.innerClass(simpleName);
innerClassesAccessModifiers.put(innerClass, accessModifiers);
return innerClass;
} | java |
public void add(ClassData classData) {
checkRegistered(classData.type());
innerClasses.put(classData.type(), classData);
} | java |
public void registerAsInnerClass(ClassVisitor visitor, TypeInfo innerClass) {
checkRegistered(innerClass);
doRegister(visitor, innerClass);
} | java |
public void registerAllInnerClasses(ClassVisitor visitor) {
for (Map.Entry<TypeInfo, Integer> entry : innerClassesAccessModifiers.entrySet()) {
TypeInfo innerClass = entry.getKey();
doRegister(visitor, innerClass);
}
} | java |
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())
.setLo... | java |
private ImmutableList<SoyMsgPart> compactParts(ImmutableList<SoyMsgPart> parts) {
ImmutableList.Builder<SoyMsgPart> builder = ImmutableList.builder();
for (SoyMsgPart part : parts) {
builder.add(compactPart(part));
}
return builder.build();
} | java |
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 = ... | java |
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);
}
thro... | java |
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 IllegalArgumen... | java |
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);
} | java |
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... | java |
@CheckReturnValue
protected Statement generateFunctionBody(TemplateNode node, String alias) {
ImmutableList.Builder<Statement> bodyStatements = ImmutableList.builder();
bodyStatements.add(
Statement.assign(
JsRuntime.OPT_IJ_DATA,
id("opt_ijData_deprecated")
.or(... | java |
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)
... | java |
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(... | java |
@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.... | java |
public static PluginResolver nullResolver(Mode mode, ErrorReporter reporter) {
return new PluginResolver(
mode, ImmutableMap.of(), ImmutableMap.of(), ImmutableMap.of(), reporter);
} | java |
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 = createP... | java |
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 (so... | java |
public void setPrintDirective(SoyPrintDirective printDirective) {
checkState(this.printDirective == null, "setPrintDirective has already been called");
checkArgument(name.identifier().equals(printDirective.getName()));
this.printDirective = checkNotNull(printDirective);
} | java |
LocalVariableStack addVariable(String name, PyExpr varExpression) {
Preconditions.checkState(!localVarExprs.isEmpty());
localVarExprs.peek().put(name, varExpression);
return this;
} | java |
public Context derive(HtmlContext state) {
return state == this.state ? this : toBuilder().withState(state).build();
} | java |
public Context derive(JsFollowingSlash slashType) {
return slashType == this.slashType ? this : toBuilder().withSlashType(slashType).build();
} | java |
public Context derive(UriPart uriPart) {
return uriPart == this.uriPart ? this : toBuilder().withUriPart(uriPart).build();
} | java |
public Context derive(HtmlHtmlAttributePosition htmlHtmlAttributePosition) {
return htmlHtmlAttributePosition == this.htmlHtmlAttributePosition
? this
: toBuilder().withHtmlHtmlAttributePosition(htmlHtmlAttributePosition).build();
} | java |
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 ... | java |
static Context computeContextAfterAttributeDelimiter(
ElementType elType,
AttributeType attrType,
AttributeEndDelimiter delim,
UriType uriType,
int templateNestDepth) {
HtmlContext state;
JsFollowingSlash slash = JsFollowingSlash.NONE;
UriPart uriPart = UriPart.NONE;
switch... | java |
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
/... | java |
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 CS... | java |
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_... | java |
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.DANGE... | java |
@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(El... | java |
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 ... | java |
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 wh... | java |
public SanitizedContentKind getMostAppropriateContentKind() {
SanitizedContentKind kind = STATE_TO_CONTENT_KIND.get(state);
if (kind != null && isValidStartContextForContentKindLoose(kind)) {
return kind;
}
return SanitizedContentKind.TEXT;
} | java |
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... | java |
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 ... | java |
public void increaseIndent(int numStops) {
indentLen += numStops * indentIncrementLen;
Preconditions.checkState(0 <= indentLen && indentLen <= MAX_INDENT_LEN);
indent = SPACES.substring(0, indentLen);
} | java |
public IndentedLinesBuilder appendParts(Object... parts) {
for (Object part : parts) {
sb.append(part);
}
return this;
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.