Revert "feat(Compiler): case sensitive html parser"

This reverts commit 86aeb8be0a.
This commit is contained in:
vsavkin 2015-11-16 14:37:00 -08:00
parent 0611239a0e
commit 4e1d9c93df
14 changed files with 669 additions and 1673 deletions

View File

@ -1,25 +1,23 @@
import {isPresent} from 'angular2/src/facade/lang';
import {ParseSourceSpan} from './parse_util';
export interface HtmlAst {
sourceSpan: ParseSourceSpan;
sourceInfo: string;
visit(visitor: HtmlAstVisitor, context: any): any;
}
export class HtmlTextAst implements HtmlAst {
constructor(public value: string, public sourceSpan: ParseSourceSpan) {}
constructor(public value: string, public sourceInfo: string) {}
visit(visitor: HtmlAstVisitor, context: any): any { return visitor.visitText(this, context); }
}
export class HtmlAttrAst implements HtmlAst {
constructor(public name: string, public value: string, public sourceSpan: ParseSourceSpan) {}
constructor(public name: string, public value: string, public sourceInfo: string) {}
visit(visitor: HtmlAstVisitor, context: any): any { return visitor.visitAttr(this, context); }
}
export class HtmlElementAst implements HtmlAst {
constructor(public name: string, public attrs: HtmlAttrAst[], public children: HtmlAst[],
public sourceSpan: ParseSourceSpan) {}
public sourceInfo: string) {}
visit(visitor: HtmlAstVisitor, context: any): any { return visitor.visitElement(this, context); }
}

View File

@ -1,478 +0,0 @@
import {
StringWrapper,
NumberWrapper,
isPresent,
isBlank,
CONST_EXPR,
serializeEnum
} from 'angular2/src/facade/lang';
import {BaseException} from 'angular2/src/facade/exceptions';
import {ParseLocation, ParseError, ParseSourceFile, ParseSourceSpan} from './parse_util';
import {getHtmlTagDefinition, HtmlTagContentType, NAMED_ENTITIES} from './html_tags';
export enum HtmlTokenType {
TAG_OPEN_START,
TAG_OPEN_END,
TAG_OPEN_END_VOID,
TAG_CLOSE,
TEXT,
ESCAPABLE_RAW_TEXT,
RAW_TEXT,
COMMENT_START,
COMMENT_END,
CDATA_START,
CDATA_END,
ATTR_NAME,
ATTR_VALUE,
DOC_TYPE,
EOF
}
export class HtmlToken {
constructor(public type: HtmlTokenType, public parts: string[],
public sourceSpan: ParseSourceSpan) {}
}
export class HtmlTokenError extends ParseError {
constructor(errorMsg: string, public tokenType: HtmlTokenType, location: ParseLocation) {
super(location, errorMsg);
}
}
export class HtmlTokenizeResult {
constructor(public tokens: HtmlToken[], public errors: HtmlTokenError[]) {}
}
export function tokenizeHtml(sourceContent: string, sourceUrl: string): HtmlTokenizeResult {
return new _HtmlTokenizer(new ParseSourceFile(sourceContent, sourceUrl)).tokenize();
}
const $EOF = 0;
const $TAB = 9;
const $LF = 10;
const $CR = 13;
const $SPACE = 32;
const $BANG = 33;
const $DQ = 34;
const $$ = 36;
const $AMPERSAND = 38;
const $SQ = 39;
const $MINUS = 45;
const $SLASH = 47;
const $0 = 48;
const $SEMICOLON = 59;
const $9 = 57;
const $COLON = 58;
const $LT = 60;
const $EQ = 61;
const $GT = 62;
const $QUESTION = 63;
const $A = 65;
const $Z = 90;
const $LBRACKET = 91;
const $RBRACKET = 93;
const $a = 97;
const $z = 122;
const $NBSP = 160;
function unexpectedCharacterErrorMsg(charCode: number): string {
var char = charCode === $EOF ? 'EOF' : StringWrapper.fromCharCode(charCode);
return `Unexpected character "${char}"`;
}
function unknownEntityErrorMsg(entitySrc: string): string {
return `Unknown entity "${entitySrc}"`;
}
class ControlFlowError {
constructor(public error: HtmlTokenError) {}
}
// See http://www.w3.org/TR/html51/syntax.html#writing
class _HtmlTokenizer {
private input: string;
private inputLowercase: string;
private length: number;
// Note: this is always lowercase!
private peek: number = -1;
private index: number = -1;
private line: number = 0;
private column: number = -1;
private currentTokenStart: ParseLocation;
private currentTokenType: HtmlTokenType;
tokens: HtmlToken[] = [];
errors: HtmlTokenError[] = [];
constructor(private file: ParseSourceFile) {
this.input = file.content;
this.inputLowercase = file.content.toLowerCase();
this.length = file.content.length;
this._advance();
}
tokenize(): HtmlTokenizeResult {
while (this.peek !== $EOF) {
var start = this._getLocation();
try {
if (this._attemptChar($LT)) {
if (this._attemptChar($BANG)) {
if (this._attemptChar($LBRACKET)) {
this._consumeCdata(start);
} else if (this._attemptChar($MINUS)) {
this._consumeComment(start);
} else {
this._consumeDocType(start);
}
} else if (this._attemptChar($SLASH)) {
this._consumeTagClose(start);
} else {
this._consumeTagOpen(start);
}
} else {
this._consumeText();
}
} catch (e) {
if (e instanceof ControlFlowError) {
this.errors.push(e.error);
} else {
throw e;
}
}
}
this._beginToken(HtmlTokenType.EOF);
this._endToken([]);
return new HtmlTokenizeResult(this.tokens, this.errors);
}
private _getLocation(): ParseLocation {
return new ParseLocation(this.file, this.index, this.line, this.column);
}
private _beginToken(type: HtmlTokenType, start: ParseLocation = null) {
if (isBlank(start)) {
start = this._getLocation();
}
this.currentTokenStart = start;
this.currentTokenType = type;
}
private _endToken(parts: string[], end: ParseLocation = null): HtmlToken {
if (isBlank(end)) {
end = this._getLocation();
}
var token = new HtmlToken(this.currentTokenType, parts,
new ParseSourceSpan(this.currentTokenStart, end));
this.tokens.push(token);
this.currentTokenStart = null;
this.currentTokenType = null;
return token;
}
private _createError(msg: string, position: ParseLocation): ControlFlowError {
var error = new HtmlTokenError(msg, this.currentTokenType, position);
this.currentTokenStart = null;
this.currentTokenType = null;
return new ControlFlowError(error);
}
private _advance() {
if (this.index >= this.length) {
throw this._createError(unexpectedCharacterErrorMsg($EOF), this._getLocation());
}
if (this.peek === $LF) {
this.line++;
this.column = 0;
} else if (this.peek !== $LF && this.peek !== $CR) {
this.column++;
}
this.index++;
this.peek = this.index >= this.length ? $EOF : StringWrapper.charCodeAt(this.inputLowercase,
this.index);
}
private _attemptChar(charCode: number): boolean {
if (this.peek === charCode) {
this._advance();
return true;
}
return false;
}
private _requireChar(charCode: number) {
var location = this._getLocation();
if (!this._attemptChar(charCode)) {
throw this._createError(unexpectedCharacterErrorMsg(this.peek), location);
}
}
private _attemptChars(chars: string): boolean {
for (var i = 0; i < chars.length; i++) {
if (!this._attemptChar(StringWrapper.charCodeAt(chars, i))) {
return false;
}
}
return true;
}
private _requireChars(chars: string) {
var location = this._getLocation();
if (!this._attemptChars(chars)) {
throw this._createError(unexpectedCharacterErrorMsg(this.peek), location);
}
}
private _attemptUntilFn(predicate: Function) {
while (!predicate(this.peek)) {
this._advance();
}
}
private _requireUntilFn(predicate: Function, len: number) {
var start = this._getLocation();
this._attemptUntilFn(predicate);
if (this.index - start.offset < len) {
throw this._createError(unexpectedCharacterErrorMsg(this.peek), start);
}
}
private _attemptUntilChar(char: number) {
while (this.peek !== char) {
this._advance();
}
}
private _readChar(decodeEntities: boolean): string {
if (decodeEntities && this.peek === $AMPERSAND) {
var start = this._getLocation();
this._attemptUntilChar($SEMICOLON);
this._advance();
var entitySrc = this.input.substring(start.offset + 1, this.index - 1);
var decodedEntity = decodeEntity(entitySrc);
if (isPresent(decodedEntity)) {
return decodedEntity;
} else {
throw this._createError(unknownEntityErrorMsg(entitySrc), start);
}
} else {
var index = this.index;
this._advance();
return this.input[index];
}
}
private _consumeRawText(decodeEntities: boolean, firstCharOfEnd: number,
attemptEndRest: Function): HtmlToken {
var tagCloseStart;
var textStart = this._getLocation();
this._beginToken(decodeEntities ? HtmlTokenType.ESCAPABLE_RAW_TEXT : HtmlTokenType.RAW_TEXT,
textStart);
var parts = [];
while (true) {
tagCloseStart = this._getLocation();
if (this._attemptChar(firstCharOfEnd) && attemptEndRest()) {
break;
}
if (this.index > tagCloseStart.offset) {
parts.push(this.input.substring(tagCloseStart.offset, this.index));
}
while (this.peek !== firstCharOfEnd) {
parts.push(this._readChar(decodeEntities));
}
}
return this._endToken([parts.join('')], tagCloseStart);
}
private _consumeComment(start: ParseLocation) {
this._beginToken(HtmlTokenType.COMMENT_START, start);
this._requireChar($MINUS);
this._endToken([]);
var textToken = this._consumeRawText(false, $MINUS, () => this._attemptChars('->'));
this._beginToken(HtmlTokenType.COMMENT_END, textToken.sourceSpan.end);
this._endToken([]);
}
private _consumeCdata(start: ParseLocation) {
this._beginToken(HtmlTokenType.CDATA_START, start);
this._requireChars('cdata[');
this._endToken([]);
var textToken = this._consumeRawText(false, $RBRACKET, () => this._attemptChars(']>'));
this._beginToken(HtmlTokenType.CDATA_END, textToken.sourceSpan.end);
this._endToken([]);
}
private _consumeDocType(start: ParseLocation) {
this._beginToken(HtmlTokenType.DOC_TYPE, start);
this._attemptUntilChar($GT);
this._advance();
this._endToken([this.input.substring(start.offset + 2, this.index - 1)]);
}
private _consumePrefixAndName(): string[] {
var nameOrPrefixStart = this.index;
var prefix = null;
while (this.peek !== $COLON && !isPrefixEnd(this.peek)) {
this._advance();
}
var nameStart;
if (this.peek === $COLON) {
this._advance();
prefix = this.input.substring(nameOrPrefixStart, this.index - 1);
nameStart = this.index;
} else {
nameStart = nameOrPrefixStart;
}
this._requireUntilFn(isNameEnd, this.index === nameStart ? 1 : 0);
var name = this.input.substring(nameStart, this.index);
return [prefix, name];
}
private _consumeTagOpen(start: ParseLocation) {
this._attemptUntilFn(isNotWhitespace);
var nameStart = this.index;
this._consumeTagOpenStart(start);
var lowercaseTagName = this.inputLowercase.substring(nameStart, this.index);
this._attemptUntilFn(isNotWhitespace);
while (this.peek !== $SLASH && this.peek !== $GT) {
this._consumeAttributeName();
this._attemptUntilFn(isNotWhitespace);
if (this._attemptChar($EQ)) {
this._attemptUntilFn(isNotWhitespace);
this._consumeAttributeValue();
}
this._attemptUntilFn(isNotWhitespace);
}
this._consumeTagOpenEnd();
var contentTokenType = getHtmlTagDefinition(lowercaseTagName).contentType;
if (contentTokenType === HtmlTagContentType.RAW_TEXT) {
this._consumeRawTextWithTagClose(lowercaseTagName, false);
} else if (contentTokenType === HtmlTagContentType.ESCAPABLE_RAW_TEXT) {
this._consumeRawTextWithTagClose(lowercaseTagName, true);
}
}
private _consumeRawTextWithTagClose(lowercaseTagName: string, decodeEntities: boolean) {
var textToken = this._consumeRawText(decodeEntities, $LT, () => {
if (!this._attemptChar($SLASH)) return false;
this._attemptUntilFn(isNotWhitespace);
if (!this._attemptChars(lowercaseTagName)) return false;
this._attemptUntilFn(isNotWhitespace);
if (!this._attemptChar($GT)) return false;
return true;
});
this._beginToken(HtmlTokenType.TAG_CLOSE, textToken.sourceSpan.end);
this._endToken([null, lowercaseTagName]);
}
private _consumeTagOpenStart(start: ParseLocation) {
this._beginToken(HtmlTokenType.TAG_OPEN_START, start);
var parts = this._consumePrefixAndName();
this._endToken(parts);
}
private _consumeAttributeName() {
this._beginToken(HtmlTokenType.ATTR_NAME);
var prefixAndName = this._consumePrefixAndName();
this._endToken(prefixAndName);
}
private _consumeAttributeValue() {
this._beginToken(HtmlTokenType.ATTR_VALUE);
var value;
if (this.peek === $SQ || this.peek === $DQ) {
var quoteChar = this.peek;
this._advance();
var parts = [];
while (this.peek !== quoteChar) {
parts.push(this._readChar(true));
}
value = parts.join('');
this._advance();
} else {
var valueStart = this.index;
this._requireUntilFn(isNameEnd, 1);
value = this.input.substring(valueStart, this.index);
}
this._endToken([value]);
}
private _consumeTagOpenEnd() {
var tokenType =
this._attemptChar($SLASH) ? HtmlTokenType.TAG_OPEN_END_VOID : HtmlTokenType.TAG_OPEN_END;
this._beginToken(tokenType);
this._requireChar($GT);
this._endToken([]);
}
private _consumeTagClose(start: ParseLocation) {
this._beginToken(HtmlTokenType.TAG_CLOSE, start);
this._attemptUntilFn(isNotWhitespace);
var prefixAndName;
prefixAndName = this._consumePrefixAndName();
this._attemptUntilFn(isNotWhitespace);
this._requireChar($GT);
this._endToken(prefixAndName);
}
private _consumeText() {
var start = this._getLocation();
this._beginToken(HtmlTokenType.TEXT, start);
var parts = [this._readChar(true)];
while (!isTextEnd(this.peek)) {
parts.push(this._readChar(true));
}
this._endToken([parts.join('')]);
}
}
function isNotWhitespace(code: number): boolean {
return !isWhitespace(code) || code === $EOF;
}
function isWhitespace(code: number): boolean {
return (code >= $TAB && code <= $SPACE) || (code === $NBSP);
}
function isNameEnd(code: number): boolean {
return isWhitespace(code) || code === $GT || code === $SLASH || code === $SQ || code === $DQ ||
code === $EQ
}
function isPrefixEnd(code: number): boolean {
return (code < $a || $z < code) && (code < $A || $Z < code) && (code < $0 || code > $9);
}
function isTextEnd(code: number): boolean {
return code === $LT || code === $EOF;
}
function decodeEntity(entity: string): string {
var i = 0;
var isNumber = entity.length > i && entity[i] == '#';
if (isNumber) i++;
var isHex = entity.length > i && entity[i] == 'x';
if (isHex) i++;
var value = entity.substring(i);
var result = null;
if (isNumber) {
var charCode;
try {
charCode = NumberWrapper.parseInt(value, isHex ? 16 : 10);
} catch (e) {
return null;
}
result = StringWrapper.fromCharCode(charCode);
} else {
result = NAMED_ENTITIES[value];
}
if (isPresent(result)) {
return result;
} else {
return null;
}
}

View File

@ -1,248 +1,118 @@
import {
isPresent,
isBlank,
StringWrapper,
stringify,
assertionsEnabled,
StringJoiner,
RegExpWrapper,
serializeEnum,
CONST_EXPR
StringJoiner
} from 'angular2/src/facade/lang';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {ListWrapper} from 'angular2/src/facade/collection';
import {HtmlAst, HtmlAttrAst, HtmlTextAst, HtmlElementAst} from './html_ast';
import {
HtmlAst,
HtmlAttrAst,
HtmlTextAst,
HtmlElementAst,
HtmlAstVisitor,
htmlVisitAll
} from './html_ast';
import {escapeDoubleQuoteString} from './util';
import {Injectable} from 'angular2/src/core/di';
import {HtmlToken, HtmlTokenType, tokenizeHtml} from './html_lexer';
import {ParseError, ParseLocation, ParseSourceSpan} from './parse_util';
import {HtmlTagDefinition, getHtmlTagDefinition} from './html_tags';
// TODO: remove this, just provide a plain error message!
export enum HtmlTreeErrorType {
UnexpectedClosingTag
}
const HTML_ERROR_TYPE_MSGS = CONST_EXPR(['Unexpected closing tag']);
export class HtmlTreeError extends ParseError {
static create(type: HtmlTreeErrorType, elementName: string,
location: ParseLocation): HtmlTreeError {
return new HtmlTreeError(type, HTML_ERROR_TYPE_MSGS[serializeEnum(type)], elementName,
location);
}
constructor(public type: HtmlTreeErrorType, msg: string, public elementName: string,
location: ParseLocation) {
super(location, msg);
}
}
export class HtmlParseTreeResult {
constructor(public rootNodes: HtmlAst[], public errors: ParseError[]) {}
}
@Injectable()
export class HtmlParser {
parse(sourceContent: string, sourceUrl: string): HtmlParseTreeResult {
var tokensAndErrors = tokenizeHtml(sourceContent, sourceUrl);
var treeAndErrors = new TreeBuilder(tokensAndErrors.tokens).build();
return new HtmlParseTreeResult(treeAndErrors.rootNodes, (<ParseError[]>tokensAndErrors.errors)
.concat(treeAndErrors.errors));
parse(template: string, sourceInfo: string): HtmlAst[] {
var root = DOM.createTemplate(template);
return parseChildNodes(root, sourceInfo);
}
unparse(nodes: HtmlAst[]): string {
var visitor = new UnparseVisitor();
var parts = [];
htmlVisitAll(visitor, nodes, parts);
return parts.join('');
}
}
var NS_PREFIX_RE = /^@[^:]+/g;
function parseText(text: Text, indexInParent: number, parentSourceInfo: string): HtmlTextAst {
// TODO(tbosch): add source row/column source info from parse5 / package:html
var value = DOM.getText(text);
return new HtmlTextAst(value,
`${parentSourceInfo} > #text(${value}):nth-child(${indexInParent})`);
}
class TreeBuilder {
private index: number = -1;
private length: number;
private peek: HtmlToken;
function parseAttr(element: Element, parentSourceInfo: string, attrName: string,
attrValue: string): HtmlAttrAst {
// TODO(tbosch): add source row/column source info from parse5 / package:html
return new HtmlAttrAst(attrName, attrValue, `${parentSourceInfo}[${attrName}=${attrValue}]`);
}
private rootNodes: HtmlAst[] = [];
private errors: HtmlTreeError[] = [];
function parseElement(element: Element, indexInParent: number,
parentSourceInfo: string): HtmlElementAst {
// normalize nodename always as lower case so that following build steps
// can rely on this
var nodeName = DOM.nodeName(element).toLowerCase();
// TODO(tbosch): add source row/column source info from parse5 / package:html
var sourceInfo = `${parentSourceInfo} > ${nodeName}:nth-child(${indexInParent})`;
var attrs = parseAttrs(element, sourceInfo);
private elementStack: HtmlElementAst[] = [];
var childNodes = parseChildNodes(element, sourceInfo);
return new HtmlElementAst(nodeName, attrs, childNodes, sourceInfo);
}
constructor(private tokens: HtmlToken[]) { this._advance(); }
function parseAttrs(element: Element, elementSourceInfo: string): HtmlAttrAst[] {
// Note: sort the attributes early in the pipeline to get
// consistent results throughout the pipeline, as attribute order is not defined
// in DOM parsers!
var attrMap = DOM.attributeMap(element);
var attrList: string[][] = [];
attrMap.forEach((value, name) => attrList.push([name, value]));
attrList.sort((entry1, entry2) => StringWrapper.compare(entry1[0], entry2[0]));
return attrList.map(entry => parseAttr(element, elementSourceInfo, entry[0], entry[1]));
}
build(): HtmlParseTreeResult {
while (this.peek.type !== HtmlTokenType.EOF) {
if (this.peek.type === HtmlTokenType.TAG_OPEN_START) {
this._consumeStartTag(this._advance());
} else if (this.peek.type === HtmlTokenType.TAG_CLOSE) {
this._consumeEndTag(this._advance());
} else if (this.peek.type === HtmlTokenType.CDATA_START) {
this._consumeCdata(this._advance());
} else if (this.peek.type === HtmlTokenType.COMMENT_START) {
this._consumeComment(this._advance());
} else if (this.peek.type === HtmlTokenType.TEXT ||
this.peek.type === HtmlTokenType.RAW_TEXT ||
this.peek.type === HtmlTokenType.ESCAPABLE_RAW_TEXT) {
this._consumeText(this._advance());
} else {
// Skip all other tokens...
this._advance();
}
function parseChildNodes(element: Element, parentSourceInfo: string): HtmlAst[] {
var root = DOM.templateAwareRoot(element);
var childNodes = DOM.childNodesAsList(root);
var result = [];
var index = 0;
childNodes.forEach(childNode => {
var childResult = null;
if (DOM.isTextNode(childNode)) {
var text = <Text>childNode;
childResult = parseText(text, index, parentSourceInfo);
} else if (DOM.isElementNode(childNode)) {
var el = <Element>childNode;
childResult = parseElement(el, index, parentSourceInfo);
}
return new HtmlParseTreeResult(this.rootNodes, this.errors);
}
private _advance(): HtmlToken {
var prev = this.peek;
if (this.index < this.tokens.length - 1) {
// Note: there is always an EOF token at the end
this.index++;
if (isPresent(childResult)) {
// Won't have a childResult for e.g. comment nodes
result.push(childResult);
}
this.peek = this.tokens[this.index];
return prev;
}
index++;
});
return result;
}
private _advanceIf(type: HtmlTokenType): HtmlToken {
if (this.peek.type === type) {
return this._advance();
class UnparseVisitor implements HtmlAstVisitor {
visitElement(ast: HtmlElementAst, parts: string[]): any {
parts.push(`<${ast.name}`);
var attrs = [];
htmlVisitAll(this, ast.attrs, attrs);
if (ast.attrs.length > 0) {
parts.push(' ');
parts.push(attrs.join(' '));
}
parts.push(`>`);
htmlVisitAll(this, ast.children, parts);
parts.push(`</${ast.name}>`);
return null;
}
private _consumeCdata(startToken: HtmlToken) {
this._consumeText(this._advance());
this._advanceIf(HtmlTokenType.CDATA_END);
visitAttr(ast: HtmlAttrAst, parts: string[]): any {
parts.push(`${ast.name}=${escapeDoubleQuoteString(ast.value)}`);
return null;
}
private _consumeComment(startToken: HtmlToken) {
this._advanceIf(HtmlTokenType.RAW_TEXT);
this._advanceIf(HtmlTokenType.COMMENT_END);
}
private _consumeText(token: HtmlToken) {
this._addToParent(new HtmlTextAst(token.parts[0], token.sourceSpan));
}
private _consumeStartTag(startTagToken: HtmlToken) {
var prefix = startTagToken.parts[0];
var name = startTagToken.parts[1];
var attrs = [];
while (this.peek.type === HtmlTokenType.ATTR_NAME) {
attrs.push(this._consumeAttr(this._advance()));
}
var fullName = elementName(prefix, name, this._getParentElement());
var voidElement = false;
// Note: There could have been a tokenizer error
// so that we don't get a token for the end tag...
if (this.peek.type === HtmlTokenType.TAG_OPEN_END_VOID) {
this._advance();
voidElement = true;
} else if (this.peek.type === HtmlTokenType.TAG_OPEN_END) {
this._advance();
voidElement = false;
}
var end = this.peek.sourceSpan.start;
var el = new HtmlElementAst(fullName, attrs, [],
new ParseSourceSpan(startTagToken.sourceSpan.start, end));
this._pushElement(el);
if (voidElement) {
this._popElement(fullName);
}
}
private _pushElement(el: HtmlElementAst) {
var stackIndex = this.elementStack.length - 1;
while (stackIndex >= 0) {
var parentEl = this.elementStack[stackIndex];
if (!getHtmlTagDefinition(parentEl.name).isClosedByChild(el.name)) {
break;
}
stackIndex--;
}
this.elementStack.splice(stackIndex, this.elementStack.length - 1 - stackIndex);
var tagDef = getHtmlTagDefinition(el.name);
var parentEl = this._getParentElement();
if (tagDef.requireExtraParent(isPresent(parentEl) ? parentEl.name : null)) {
var newParent = new HtmlElementAst(tagDef.requiredParent, [], [el], el.sourceSpan);
this._addToParent(newParent);
this.elementStack.push(newParent);
this.elementStack.push(el);
} else {
this._addToParent(el);
this.elementStack.push(el);
}
}
private _consumeEndTag(endTagToken: HtmlToken) {
var fullName =
elementName(endTagToken.parts[0], endTagToken.parts[1], this._getParentElement());
if (!this._popElement(fullName)) {
this.errors.push(HtmlTreeError.create(HtmlTreeErrorType.UnexpectedClosingTag, fullName,
endTagToken.sourceSpan.start));
}
}
private _popElement(fullName: string): boolean {
var stackIndex = this.elementStack.length - 1;
var hasError = false;
while (stackIndex >= 0) {
var el = this.elementStack[stackIndex];
if (el.name == fullName) {
break;
}
if (!getHtmlTagDefinition(el.name).closedByParent) {
hasError = true;
break;
}
stackIndex--;
}
if (!hasError) {
this.elementStack.splice(stackIndex, this.elementStack.length - stackIndex);
}
return !hasError;
}
private _consumeAttr(attrName: HtmlToken): HtmlAttrAst {
var fullName = elementName(attrName.parts[0], attrName.parts[1], null);
var end = attrName.sourceSpan.end;
var value = '';
if (this.peek.type === HtmlTokenType.ATTR_VALUE) {
var valueToken = this._advance();
value = valueToken.parts[0];
end = valueToken.sourceSpan.end;
}
return new HtmlAttrAst(fullName, value, new ParseSourceSpan(attrName.sourceSpan.start, end));
}
private _getParentElement(): HtmlElementAst {
return this.elementStack.length > 0 ? ListWrapper.last(this.elementStack) : null;
}
private _addToParent(node: HtmlAst) {
var parent = this._getParentElement();
if (isPresent(parent)) {
parent.children.push(node);
} else {
this.rootNodes.push(node);
}
visitText(ast: HtmlTextAst, parts: string[]): any {
parts.push(ast.value);
return null;
}
}
function elementName(prefix: string, localName: string, parentElement: HtmlElementAst) {
if (isBlank(prefix)) {
prefix = getHtmlTagDefinition(localName).implicitNamespacePrefix;
}
if (isBlank(prefix) && isPresent(parentElement)) {
prefix = namespacePrefix(parentElement.name);
}
if (isPresent(prefix)) {
return `@${prefix}:${localName}`;
} else {
return localName;
}
}
function namespacePrefix(elementName: string): string {
var match = RegExpWrapper.firstMatch(NS_PREFIX_RE, elementName);
return isBlank(match) ? null : match[1];
}

View File

@ -1,69 +0,0 @@
import {isPresent, isBlank, normalizeBool, CONST_EXPR} from 'angular2/src/facade/lang';
// TODO: fill this!
export const NAMED_ENTITIES: {[key: string]: string} = <any>CONST_EXPR({'amp': '&'});
export enum HtmlTagContentType {
RAW_TEXT,
ESCAPABLE_RAW_TEXT,
PARSABLE_DATA
}
export class HtmlTagDefinition {
private closedByChildren: {[key: string]: boolean} = {};
public closedByParent: boolean;
public requiredParent: string;
public implicitNamespacePrefix: string;
public contentType: HtmlTagContentType;
constructor({closedByChildren, requiredParent, implicitNamespacePrefix, contentType}: {
closedByChildren?: string[],
requiredParent?: string,
implicitNamespacePrefix?: string,
contentType?: HtmlTagContentType
} = {}) {
if (isPresent(closedByChildren)) {
closedByChildren.forEach(tagName => this.closedByChildren[tagName] = true);
}
this.closedByParent = isPresent(closedByChildren) && closedByChildren.length > 0;
this.requiredParent = requiredParent;
this.implicitNamespacePrefix = implicitNamespacePrefix;
this.contentType = isPresent(contentType) ? contentType : HtmlTagContentType.PARSABLE_DATA;
}
requireExtraParent(currentParent: string) {
return isPresent(this.requiredParent) &&
(isBlank(currentParent) || this.requiredParent != currentParent.toLocaleLowerCase());
}
isClosedByChild(name: string) {
return normalizeBool(this.closedByChildren['*']) ||
normalizeBool(this.closedByChildren[name.toLowerCase()]);
}
}
// TODO: Fill this table using
// https://github.com/greim/html-tokenizer/blob/master/parser.js
// and http://www.w3.org/TR/html51/syntax.html#optional-tags
var TAG_DEFINITIONS: {[key: string]: HtmlTagDefinition} = {
'link': new HtmlTagDefinition({closedByChildren: ['*']}),
'ng-content': new HtmlTagDefinition({closedByChildren: ['*']}),
'img': new HtmlTagDefinition({closedByChildren: ['*']}),
'input': new HtmlTagDefinition({closedByChildren: ['*']}),
'p': new HtmlTagDefinition({closedByChildren: ['p']}),
'tr': new HtmlTagDefinition({closedByChildren: ['tr'], requiredParent: 'tbody'}),
'col': new HtmlTagDefinition({closedByChildren: ['col'], requiredParent: 'colgroup'}),
'svg': new HtmlTagDefinition({implicitNamespacePrefix: 'svg'}),
'math': new HtmlTagDefinition({implicitNamespacePrefix: 'math'}),
'style': new HtmlTagDefinition({contentType: HtmlTagContentType.RAW_TEXT}),
'script': new HtmlTagDefinition({contentType: HtmlTagContentType.RAW_TEXT}),
'title': new HtmlTagDefinition({contentType: HtmlTagContentType.ESCAPABLE_RAW_TEXT}),
'textarea': new HtmlTagDefinition({contentType: HtmlTagContentType.ESCAPABLE_RAW_TEXT})
};
var DEFAULT_TAG_DEFINITION = new HtmlTagDefinition();
export function getHtmlTagDefinition(tagName: string): HtmlTagDefinition {
var result = TAG_DEFINITIONS[tagName.toLowerCase()];
return isPresent(result) ? result : DEFAULT_TAG_DEFINITION;
}

View File

@ -1,31 +0,0 @@
import {Math} from 'angular2/src/facade/math';
export class ParseLocation {
constructor(public file: ParseSourceFile, public offset: number, public line: number,
public col: number) {}
toString() { return `${this.file.url}@${this.line}:${this.col}`; }
}
export class ParseSourceFile {
constructor(public content: string, public url: string) {}
}
export abstract class ParseError {
constructor(public location: ParseLocation, public msg: string) {}
toString(): string {
var source = this.location.file.content;
var ctxStart = Math.max(this.location.offset - 10, 0);
var ctxEnd = Math.min(this.location.offset + 10, source.length);
return `${this.msg} (${source.substring(ctxStart, ctxEnd)}): ${this.location}`;
}
}
export class ParseSourceSpan {
constructor(public start: ParseLocation, public end: ParseLocation) {}
toString(): string {
return this.start.file.content.substring(this.start.offset, this.end.offset);
}
}

View File

@ -1,35 +1,32 @@
import {AST} from 'angular2/src/core/change_detection/change_detection';
import {isPresent} from 'angular2/src/facade/lang';
import {CompileDirectiveMetadata} from './directive_metadata';
import {ParseSourceSpan} from './parse_util';
export interface TemplateAst {
sourceSpan: ParseSourceSpan;
sourceInfo: string;
visit(visitor: TemplateAstVisitor, context: any): any;
}
export class TextAst implements TemplateAst {
constructor(public value: string, public ngContentIndex: number,
public sourceSpan: ParseSourceSpan) {}
constructor(public value: string, public ngContentIndex: number, public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitText(this, context); }
}
export class BoundTextAst implements TemplateAst {
constructor(public value: AST, public ngContentIndex: number,
public sourceSpan: ParseSourceSpan) {}
constructor(public value: AST, public ngContentIndex: number, public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitBoundText(this, context);
}
}
export class AttrAst implements TemplateAst {
constructor(public name: string, public value: string, public sourceSpan: ParseSourceSpan) {}
constructor(public name: string, public value: string, public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitAttr(this, context); }
}
export class BoundElementPropertyAst implements TemplateAst {
constructor(public name: string, public type: PropertyBindingType, public value: AST,
public unit: string, public sourceSpan: ParseSourceSpan) {}
public unit: string, public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitElementProperty(this, context);
}
@ -37,7 +34,7 @@ export class BoundElementPropertyAst implements TemplateAst {
export class BoundEventAst implements TemplateAst {
constructor(public name: string, public target: string, public handler: AST,
public sourceSpan: ParseSourceSpan) {}
public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitEvent(this, context);
}
@ -51,7 +48,7 @@ export class BoundEventAst implements TemplateAst {
}
export class VariableAst implements TemplateAst {
constructor(public name: string, public value: string, public sourceSpan: ParseSourceSpan) {}
constructor(public name: string, public value: string, public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitVariable(this, context);
}
@ -62,7 +59,7 @@ export class ElementAst implements TemplateAst {
public inputs: BoundElementPropertyAst[], public outputs: BoundEventAst[],
public exportAsVars: VariableAst[], public directives: DirectiveAst[],
public children: TemplateAst[], public ngContentIndex: number,
public sourceSpan: ParseSourceSpan) {}
public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitElement(this, context);
}
@ -82,7 +79,7 @@ export class ElementAst implements TemplateAst {
export class EmbeddedTemplateAst implements TemplateAst {
constructor(public attrs: AttrAst[], public outputs: BoundEventAst[], public vars: VariableAst[],
public directives: DirectiveAst[], public children: TemplateAst[],
public ngContentIndex: number, public sourceSpan: ParseSourceSpan) {}
public ngContentIndex: number, public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitEmbeddedTemplate(this, context);
}
@ -90,7 +87,7 @@ export class EmbeddedTemplateAst implements TemplateAst {
export class BoundDirectivePropertyAst implements TemplateAst {
constructor(public directiveName: string, public templateName: string, public value: AST,
public sourceSpan: ParseSourceSpan) {}
public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitDirectiveProperty(this, context);
}
@ -100,15 +97,14 @@ export class DirectiveAst implements TemplateAst {
constructor(public directive: CompileDirectiveMetadata,
public inputs: BoundDirectivePropertyAst[],
public hostProperties: BoundElementPropertyAst[], public hostEvents: BoundEventAst[],
public exportAsVars: VariableAst[], public sourceSpan: ParseSourceSpan) {}
public exportAsVars: VariableAst[], public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitDirective(this, context);
}
}
export class NgContentAst implements TemplateAst {
constructor(public index: number, public ngContentIndex: number,
public sourceSpan: ParseSourceSpan) {}
constructor(public index: number, public ngContentIndex: number, public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitNgContent(this, context);
}

View File

@ -29,7 +29,7 @@ import {preparseElement, PreparsedElement, PreparsedElementType} from './templat
@Injectable()
export class TemplateNormalizer {
constructor(private _xhr: XHR, private _urlResolver: UrlResolver,
private _htmlParser: HtmlParser) {}
private _domParser: HtmlParser) {}
normalizeTemplate(directiveType: CompileTypeMetadata,
template: CompileTemplateMetadata): Promise<CompileTemplateMetadata> {
@ -48,14 +48,9 @@ export class TemplateNormalizer {
normalizeLoadedTemplate(directiveType: CompileTypeMetadata, templateMeta: CompileTemplateMetadata,
template: string, templateAbsUrl: string): CompileTemplateMetadata {
var rootNodesAndErrors = this._htmlParser.parse(template, directiveType.name);
if (rootNodesAndErrors.errors.length > 0) {
var errorString = rootNodesAndErrors.errors.join('\n');
throw new BaseException(`Template parse errors:\n${errorString}`);
}
var domNodes = this._domParser.parse(template, directiveType.name);
var visitor = new TemplatePreparseVisitor();
htmlVisitAll(visitor, rootNodesAndErrors.rootNodes);
htmlVisitAll(visitor, domNodes);
var allStyles = templateMeta.styles.concat(visitor.styles);
var allStyleAbsUrls =

View File

@ -19,8 +19,6 @@ import {Parser, AST, ASTWithSource} from 'angular2/src/core/change_detection/cha
import {TemplateBinding} from 'angular2/src/core/change_detection/parser/ast';
import {CompileDirectiveMetadata} from './directive_metadata';
import {HtmlParser} from './html_parser';
import {ParseSourceSpan, ParseError, ParseLocation} from './parse_util';
import {
ElementAst,
@ -71,30 +69,25 @@ const TEMPLATE_ATTR = 'template';
const TEMPLATE_ATTR_PREFIX = '*';
const CLASS_ATTR = 'class';
var PROPERTY_PARTS_SEPARATOR = '.';
var PROPERTY_PARTS_SEPARATOR = new RegExp('\\.');
const ATTRIBUTE_PREFIX = 'attr';
const CLASS_PREFIX = 'class';
const STYLE_PREFIX = 'style';
var TEXT_CSS_SELECTOR = CssSelector.parse('*')[0];
export class TemplateParseError extends ParseError {
constructor(message: string, location: ParseLocation) { super(location, message); }
}
@Injectable()
export class TemplateParser {
constructor(private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry,
private _htmlParser: HtmlParser) {}
parse(template: string, directives: CompileDirectiveMetadata[],
templateUrl: string): TemplateAst[] {
sourceInfo: string): TemplateAst[] {
var parseVisitor = new TemplateParseVisitor(directives, this._exprParser, this._schemaRegistry);
var htmlAstWithErrors = this._htmlParser.parse(template, templateUrl);
var result = htmlVisitAll(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_COMPONENT);
var errors: ParseError[] = htmlAstWithErrors.errors.concat(parseVisitor.errors);
if (errors.length > 0) {
var errorString = errors.join('\n');
var result =
htmlVisitAll(parseVisitor, this._htmlParser.parse(template, sourceInfo), EMPTY_COMPONENT);
if (parseVisitor.errors.length > 0) {
var errorString = parseVisitor.errors.join('\n');
throw new BaseException(`Template parse errors:\n${errorString}`);
}
return result;
@ -103,7 +96,7 @@ export class TemplateParser {
class TemplateParseVisitor implements HtmlAstVisitor {
selectorMatcher: SelectorMatcher;
errors: TemplateParseError[] = [];
errors: string[] = [];
directivesIndex = new Map<CompileDirectiveMetadata, number>();
ngContentCount: number = 0;
@ -118,62 +111,56 @@ class TemplateParseVisitor implements HtmlAstVisitor {
});
}
private _reportError(message: string, sourceSpan: ParseSourceSpan) {
this.errors.push(new TemplateParseError(message, sourceSpan.start));
}
private _reportError(message: string) { this.errors.push(message); }
private _parseInterpolation(value: string, sourceSpan: ParseSourceSpan): ASTWithSource {
var sourceInfo = sourceSpan.start.toString();
private _parseInterpolation(value: string, sourceInfo: string): ASTWithSource {
try {
return this._exprParser.parseInterpolation(value, sourceInfo);
} catch (e) {
this._reportError(`${e}`, sourceSpan);
this._reportError(`${e}`); // sourceInfo is already contained in the AST
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
}
}
private _parseAction(value: string, sourceSpan: ParseSourceSpan): ASTWithSource {
var sourceInfo = sourceSpan.start.toString();
private _parseAction(value: string, sourceInfo: string): ASTWithSource {
try {
return this._exprParser.parseAction(value, sourceInfo);
} catch (e) {
this._reportError(`${e}`, sourceSpan);
this._reportError(`${e}`); // sourceInfo is already contained in the AST
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
}
}
private _parseBinding(value: string, sourceSpan: ParseSourceSpan): ASTWithSource {
var sourceInfo = sourceSpan.start.toString();
private _parseBinding(value: string, sourceInfo: string): ASTWithSource {
try {
return this._exprParser.parseBinding(value, sourceInfo);
} catch (e) {
this._reportError(`${e}`, sourceSpan);
this._reportError(`${e}`); // sourceInfo is already contained in the AST
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
}
}
private _parseTemplateBindings(value: string, sourceSpan: ParseSourceSpan): TemplateBinding[] {
var sourceInfo = sourceSpan.start.toString();
private _parseTemplateBindings(value: string, sourceInfo: string): TemplateBinding[] {
try {
return this._exprParser.parseTemplateBindings(value, sourceInfo);
} catch (e) {
this._reportError(`${e}`, sourceSpan);
this._reportError(`${e}`); // sourceInfo is already contained in the AST
return [];
}
}
visitText(ast: HtmlTextAst, component: Component): any {
var ngContentIndex = component.findNgContentIndex(TEXT_CSS_SELECTOR);
var expr = this._parseInterpolation(ast.value, ast.sourceSpan);
var expr = this._parseInterpolation(ast.value, ast.sourceInfo);
if (isPresent(expr)) {
return new BoundTextAst(expr, ngContentIndex, ast.sourceSpan);
return new BoundTextAst(expr, ngContentIndex, ast.sourceInfo);
} else {
return new TextAst(ast.value, ngContentIndex, ast.sourceSpan);
return new TextAst(ast.value, ngContentIndex, ast.sourceInfo);
}
}
visitAttr(ast: HtmlAttrAst, contex: any): any {
return new AttrAst(ast.name, ast.value, ast.sourceSpan);
return new AttrAst(ast.name, ast.value, ast.sourceInfo);
}
visitElement(element: HtmlElementAst, component: Component): any {
@ -189,7 +176,8 @@ class TemplateParseVisitor implements HtmlAstVisitor {
if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
isStyleUrlResolvable(preparsedElement.hrefAttr)) {
// Skipping stylesheets with either relative urls or package scheme as we already processed
// them in the StyleCompiler
// them
// in the StyleCompiler
return null;
}
@ -203,7 +191,6 @@ class TemplateParseVisitor implements HtmlAstVisitor {
var templateMatchableAttrs: string[][] = [];
var hasInlineTemplates = false;
var attrs = [];
element.attrs.forEach(attr => {
matchableAttrs.push([attr.name, attr.value]);
var hasBinding = this._parseAttr(attr, matchableAttrs, elementOrDirectiveProps, events, vars);
@ -217,12 +204,11 @@ class TemplateParseVisitor implements HtmlAstVisitor {
hasInlineTemplates = true;
}
});
var isTemplateElement = nodeName == TEMPLATE_ELEMENT;
var elementCssSelector = createElementCssSelector(nodeName, matchableAttrs);
var directives = this._createDirectiveAsts(
element.name, this._parseDirectives(this.selectorMatcher, elementCssSelector),
elementOrDirectiveProps, isTemplateElement ? [] : vars, element.sourceSpan);
elementOrDirectiveProps, isTemplateElement ? [] : vars, element.sourceInfo);
var elementProps: BoundElementPropertyAst[] =
this._createElementPropertyAsts(element.name, elementOrDirectiveProps, directives);
var children = htmlVisitAll(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this,
@ -232,32 +218,32 @@ class TemplateParseVisitor implements HtmlAstVisitor {
var parsedElement;
if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
parsedElement =
new NgContentAst(this.ngContentCount++, elementNgContentIndex, element.sourceSpan);
new NgContentAst(this.ngContentCount++, elementNgContentIndex, element.sourceInfo);
} else if (isTemplateElement) {
this._assertAllEventsPublishedByDirectives(directives, events);
this._assertAllEventsPublishedByDirectives(directives, events, element.sourceInfo);
this._assertNoComponentsNorElementBindingsOnTemplate(directives, elementProps,
element.sourceSpan);
element.sourceInfo);
parsedElement = new EmbeddedTemplateAst(attrs, events, vars, directives, children,
elementNgContentIndex, element.sourceSpan);
elementNgContentIndex, element.sourceInfo);
} else {
this._assertOnlyOneComponent(directives, element.sourceSpan);
this._assertOnlyOneComponent(directives, element.sourceInfo);
var elementExportAsVars = vars.filter(varAst => varAst.value.length === 0);
parsedElement =
new ElementAst(nodeName, attrs, elementProps, events, elementExportAsVars, directives,
children, elementNgContentIndex, element.sourceSpan);
children, elementNgContentIndex, element.sourceInfo);
}
if (hasInlineTemplates) {
var templateCssSelector = createElementCssSelector(TEMPLATE_ELEMENT, templateMatchableAttrs);
var templateDirectives = this._createDirectiveAsts(
element.name, this._parseDirectives(this.selectorMatcher, templateCssSelector),
templateElementOrDirectiveProps, [], element.sourceSpan);
templateElementOrDirectiveProps, [], element.sourceInfo);
var templateElementProps: BoundElementPropertyAst[] = this._createElementPropertyAsts(
element.name, templateElementOrDirectiveProps, templateDirectives);
this._assertNoComponentsNorElementBindingsOnTemplate(templateDirectives, templateElementProps,
element.sourceSpan);
element.sourceInfo);
parsedElement = new EmbeddedTemplateAst(
[], [], templateVars, templateDirectives, [parsedElement],
component.findNgContentIndex(templateCssSelector), element.sourceSpan);
component.findNgContentIndex(templateCssSelector), element.sourceInfo);
}
return parsedElement;
}
@ -273,20 +259,20 @@ class TemplateParseVisitor implements HtmlAstVisitor {
templateBindingsSource = (attr.value.length == 0) ? key : key + ' ' + attr.value;
}
if (isPresent(templateBindingsSource)) {
var bindings = this._parseTemplateBindings(templateBindingsSource, attr.sourceSpan);
var bindings = this._parseTemplateBindings(templateBindingsSource, attr.sourceInfo);
for (var i = 0; i < bindings.length; i++) {
var binding = bindings[i];
var dashCaseKey = camelCaseToDashCase(binding.key);
if (binding.keyIsVar) {
targetVars.push(
new VariableAst(dashCaseToCamelCase(binding.key), binding.name, attr.sourceSpan));
new VariableAst(dashCaseToCamelCase(binding.key), binding.name, attr.sourceInfo));
targetMatchableAttrs.push([dashCaseKey, binding.name]);
} else if (isPresent(binding.expression)) {
this._parsePropertyAst(dashCaseKey, binding.expression, attr.sourceSpan,
this._parsePropertyAst(dashCaseKey, binding.expression, attr.sourceInfo,
targetMatchableAttrs, targetProps);
} else {
targetMatchableAttrs.push([dashCaseKey, '']);
this._parseLiteralAttr(dashCaseKey, null, attr.sourceSpan, targetProps);
this._parseLiteralAttr(dashCaseKey, null, attr.sourceInfo, targetProps);
}
}
return true;
@ -304,44 +290,44 @@ class TemplateParseVisitor implements HtmlAstVisitor {
if (isPresent(bindParts)) {
hasBinding = true;
if (isPresent(bindParts[1])) { // match: bind-prop
this._parseProperty(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs,
this._parseProperty(bindParts[5], attrValue, attr.sourceInfo, targetMatchableAttrs,
targetProps);
} else if (isPresent(
bindParts[2])) { // match: var-name / var-name="iden" / #name / #name="iden"
var identifier = bindParts[5];
this._parseVariable(identifier, attrValue, attr.sourceSpan, targetVars);
this._parseVariable(identifier, attrValue, attr.sourceInfo, targetVars);
} else if (isPresent(bindParts[3])) { // match: on-event
this._parseEvent(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs,
this._parseEvent(bindParts[5], attrValue, attr.sourceInfo, targetMatchableAttrs,
targetEvents);
} else if (isPresent(bindParts[4])) { // match: bindon-prop
this._parseProperty(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs,
this._parseProperty(bindParts[5], attrValue, attr.sourceInfo, targetMatchableAttrs,
targetProps);
this._parseAssignmentEvent(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs,
this._parseAssignmentEvent(bindParts[5], attrValue, attr.sourceInfo, targetMatchableAttrs,
targetEvents);
} else if (isPresent(bindParts[6])) { // match: [(expr)]
this._parseProperty(bindParts[6], attrValue, attr.sourceSpan, targetMatchableAttrs,
this._parseProperty(bindParts[6], attrValue, attr.sourceInfo, targetMatchableAttrs,
targetProps);
this._parseAssignmentEvent(bindParts[6], attrValue, attr.sourceSpan, targetMatchableAttrs,
this._parseAssignmentEvent(bindParts[6], attrValue, attr.sourceInfo, targetMatchableAttrs,
targetEvents);
} else if (isPresent(bindParts[7])) { // match: [expr]
this._parseProperty(bindParts[7], attrValue, attr.sourceSpan, targetMatchableAttrs,
this._parseProperty(bindParts[7], attrValue, attr.sourceInfo, targetMatchableAttrs,
targetProps);
} else if (isPresent(bindParts[8])) { // match: (event)
this._parseEvent(bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs,
this._parseEvent(bindParts[8], attrValue, attr.sourceInfo, targetMatchableAttrs,
targetEvents);
}
} else {
hasBinding = this._parsePropertyInterpolation(attrName, attrValue, attr.sourceSpan,
hasBinding = this._parsePropertyInterpolation(attrName, attrValue, attr.sourceInfo,
targetMatchableAttrs, targetProps);
}
if (!hasBinding) {
this._parseLiteralAttr(attrName, attrValue, attr.sourceSpan, targetProps);
this._parseLiteralAttr(attrName, attrValue, attr.sourceInfo, targetProps);
}
return hasBinding;
}
@ -350,59 +336,59 @@ class TemplateParseVisitor implements HtmlAstVisitor {
return attrName.startsWith('data-') ? attrName.substring(5) : attrName;
}
private _parseVariable(identifier: string, value: string, sourceSpan: ParseSourceSpan,
private _parseVariable(identifier: string, value: string, sourceInfo: any,
targetVars: VariableAst[]) {
targetVars.push(new VariableAst(dashCaseToCamelCase(identifier), value, sourceSpan));
targetVars.push(new VariableAst(dashCaseToCamelCase(identifier), value, sourceInfo));
}
private _parseProperty(name: string, expression: string, sourceSpan: ParseSourceSpan,
private _parseProperty(name: string, expression: string, sourceInfo: any,
targetMatchableAttrs: string[][],
targetProps: BoundElementOrDirectiveProperty[]) {
this._parsePropertyAst(name, this._parseBinding(expression, sourceSpan), sourceSpan,
this._parsePropertyAst(name, this._parseBinding(expression, sourceInfo), sourceInfo,
targetMatchableAttrs, targetProps);
}
private _parsePropertyInterpolation(name: string, value: string, sourceSpan: ParseSourceSpan,
private _parsePropertyInterpolation(name: string, value: string, sourceInfo: any,
targetMatchableAttrs: string[][],
targetProps: BoundElementOrDirectiveProperty[]): boolean {
var expr = this._parseInterpolation(value, sourceSpan);
var expr = this._parseInterpolation(value, sourceInfo);
if (isPresent(expr)) {
this._parsePropertyAst(name, expr, sourceSpan, targetMatchableAttrs, targetProps);
this._parsePropertyAst(name, expr, sourceInfo, targetMatchableAttrs, targetProps);
return true;
}
return false;
}
private _parsePropertyAst(name: string, ast: ASTWithSource, sourceSpan: ParseSourceSpan,
private _parsePropertyAst(name: string, ast: ASTWithSource, sourceInfo: any,
targetMatchableAttrs: string[][],
targetProps: BoundElementOrDirectiveProperty[]) {
targetMatchableAttrs.push([name, ast.source]);
targetProps.push(new BoundElementOrDirectiveProperty(name, ast, false, sourceSpan));
targetProps.push(new BoundElementOrDirectiveProperty(name, ast, false, sourceInfo));
}
private _parseAssignmentEvent(name: string, expression: string, sourceSpan: ParseSourceSpan,
private _parseAssignmentEvent(name: string, expression: string, sourceInfo: string,
targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) {
this._parseEvent(`${name}-change`, `${expression}=$event`, sourceSpan, targetMatchableAttrs,
this._parseEvent(`${name}-change`, `${expression}=$event`, sourceInfo, targetMatchableAttrs,
targetEvents);
}
private _parseEvent(name: string, expression: string, sourceSpan: ParseSourceSpan,
private _parseEvent(name: string, expression: string, sourceInfo: string,
targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) {
// long format: 'target: eventName'
var parts = splitAtColon(name, [null, name]);
var target = parts[0];
var eventName = parts[1];
targetEvents.push(new BoundEventAst(dashCaseToCamelCase(eventName), target,
this._parseAction(expression, sourceSpan), sourceSpan));
this._parseAction(expression, sourceInfo), sourceInfo));
// Don't detect directives for event names for now,
// so don't add the event name to the matchableAttrs
}
private _parseLiteralAttr(name: string, value: string, sourceSpan: ParseSourceSpan,
private _parseLiteralAttr(name: string, value: string, sourceInfo: string,
targetProps: BoundElementOrDirectiveProperty[]) {
targetProps.push(new BoundElementOrDirectiveProperty(
dashCaseToCamelCase(name), this._exprParser.wrapLiteralPrimitive(value, ''), true,
sourceSpan));
dashCaseToCamelCase(name), this._exprParser.wrapLiteralPrimitive(value, sourceInfo), true,
sourceInfo));
}
private _parseDirectives(selectorMatcher: SelectorMatcher,
@ -431,15 +417,15 @@ class TemplateParseVisitor implements HtmlAstVisitor {
private _createDirectiveAsts(elementName: string, directives: CompileDirectiveMetadata[],
props: BoundElementOrDirectiveProperty[],
possibleExportAsVars: VariableAst[],
sourceSpan: ParseSourceSpan): DirectiveAst[] {
sourceInfo: string): DirectiveAst[] {
var matchedVariables = new Set<string>();
var directiveAsts = directives.map((directive: CompileDirectiveMetadata) => {
var hostProperties: BoundElementPropertyAst[] = [];
var hostEvents: BoundEventAst[] = [];
var directiveProperties: BoundDirectivePropertyAst[] = [];
this._createDirectiveHostPropertyAsts(elementName, directive.hostProperties, sourceSpan,
this._createDirectiveHostPropertyAsts(elementName, directive.hostProperties, sourceInfo,
hostProperties);
this._createDirectiveHostEventAsts(directive.hostListeners, sourceSpan, hostEvents);
this._createDirectiveHostEventAsts(directive.hostListeners, sourceInfo, hostEvents);
this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties);
var exportAsVars = [];
possibleExportAsVars.forEach((varAst) => {
@ -450,35 +436,34 @@ class TemplateParseVisitor implements HtmlAstVisitor {
}
});
return new DirectiveAst(directive, directiveProperties, hostProperties, hostEvents,
exportAsVars, sourceSpan);
exportAsVars, sourceInfo);
});
possibleExportAsVars.forEach((varAst) => {
if (varAst.value.length > 0 && !SetWrapper.has(matchedVariables, varAst.name)) {
this._reportError(`There is no directive with "exportAs" set to "${varAst.value}"`,
varAst.sourceSpan);
this._reportError(
`There is no directive with "exportAs" set to "${varAst.value}" at ${varAst.sourceInfo}`);
}
});
return directiveAsts;
}
private _createDirectiveHostPropertyAsts(elementName: string, hostProps: {[key: string]: string},
sourceSpan: ParseSourceSpan,
sourceInfo: string,
targetPropertyAsts: BoundElementPropertyAst[]) {
if (isPresent(hostProps)) {
StringMapWrapper.forEach(hostProps, (expression, propName) => {
var exprAst = this._parseBinding(expression, sourceSpan);
var exprAst = this._parseBinding(expression, sourceInfo);
targetPropertyAsts.push(
this._createElementPropertyAst(elementName, propName, exprAst, sourceSpan));
this._createElementPropertyAst(elementName, propName, exprAst, sourceInfo));
});
}
}
private _createDirectiveHostEventAsts(hostListeners: {[key: string]: string},
sourceSpan: ParseSourceSpan,
private _createDirectiveHostEventAsts(hostListeners: {[key: string]: string}, sourceInfo: string,
targetEventAsts: BoundEventAst[]) {
if (isPresent(hostListeners)) {
StringMapWrapper.forEach(hostListeners, (expression, propName) => {
this._parseEvent(propName, expression, sourceSpan, [], targetEventAsts);
this._parseEvent(propName, expression, sourceInfo, [], targetEventAsts);
});
}
}
@ -504,7 +489,7 @@ class TemplateParseVisitor implements HtmlAstVisitor {
// Bindings are optional, so this binding only needs to be set up if an expression is given.
if (isPresent(boundProp)) {
targetBoundDirectiveProps.push(new BoundDirectivePropertyAst(
dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan));
dirProp, boundProp.name, boundProp.expression, boundProp.sourceInfo));
}
});
}
@ -522,25 +507,24 @@ class TemplateParseVisitor implements HtmlAstVisitor {
props.forEach((prop: BoundElementOrDirectiveProperty) => {
if (!prop.isLiteral && isBlank(boundDirectivePropsIndex.get(prop.name))) {
boundElementProps.push(this._createElementPropertyAst(elementName, prop.name,
prop.expression, prop.sourceSpan));
prop.expression, prop.sourceInfo));
}
});
return boundElementProps;
}
private _createElementPropertyAst(elementName: string, name: string, ast: AST,
sourceSpan: ParseSourceSpan): BoundElementPropertyAst {
sourceInfo: any): BoundElementPropertyAst {
var unit = null;
var bindingType;
var boundPropertyName;
var parts = name.split(PROPERTY_PARTS_SEPARATOR);
var parts = StringWrapper.split(name, PROPERTY_PARTS_SEPARATOR);
if (parts.length === 1) {
boundPropertyName = this._schemaRegistry.getMappedPropName(dashCaseToCamelCase(parts[0]));
bindingType = PropertyBindingType.Property;
if (!this._schemaRegistry.hasProperty(elementName, boundPropertyName)) {
this._reportError(
`Can't bind to '${boundPropertyName}' since it isn't a known native property`,
sourceSpan);
`Can't bind to '${boundPropertyName}' since it isn't a known native property in ${sourceInfo}`);
}
} else if (parts[0] == ATTRIBUTE_PREFIX) {
boundPropertyName = dashCaseToCamelCase(parts[1]);
@ -554,10 +538,10 @@ class TemplateParseVisitor implements HtmlAstVisitor {
boundPropertyName = dashCaseToCamelCase(parts[1]);
bindingType = PropertyBindingType.Style;
} else {
this._reportError(`Invalid property name ${name}`, sourceSpan);
this._reportError(`Invalid property name ${name} in ${sourceInfo}`);
bindingType = null;
}
return new BoundElementPropertyAst(boundPropertyName, bindingType, ast, unit, sourceSpan);
return new BoundElementPropertyAst(boundPropertyName, bindingType, ast, unit, sourceInfo);
}
@ -572,30 +556,30 @@ class TemplateParseVisitor implements HtmlAstVisitor {
return componentTypeNames;
}
private _assertOnlyOneComponent(directives: DirectiveAst[], sourceSpan: ParseSourceSpan) {
private _assertOnlyOneComponent(directives: DirectiveAst[], sourceInfo: string) {
var componentTypeNames = this._findComponentDirectiveNames(directives);
if (componentTypeNames.length > 1) {
this._reportError(`More than one component: ${componentTypeNames.join(',')}`, sourceSpan);
this._reportError(
`More than one component: ${componentTypeNames.join(',')} in ${sourceInfo}`);
}
}
private _assertNoComponentsNorElementBindingsOnTemplate(directives: DirectiveAst[],
elementProps: BoundElementPropertyAst[],
sourceSpan: ParseSourceSpan) {
sourceInfo: string) {
var componentTypeNames: string[] = this._findComponentDirectiveNames(directives);
if (componentTypeNames.length > 0) {
this._reportError(`Components on an embedded template: ${componentTypeNames.join(',')}`,
sourceSpan);
this._reportError(
`Components on an embedded template: ${componentTypeNames.join(',')} in ${sourceInfo}`);
}
elementProps.forEach(prop => {
this._reportError(
`Property binding ${prop.name} not used by any directive on an embedded template`,
sourceSpan);
`Property binding ${prop.name} not used by any directive on an embedded template in ${prop.sourceInfo}`);
});
}
private _assertAllEventsPublishedByDirectives(directives: DirectiveAst[],
events: BoundEventAst[]) {
private _assertAllEventsPublishedByDirectives(directives: DirectiveAst[], events: BoundEventAst[],
sourceInfo: string) {
var allDirectiveEvents = new Set<string>();
directives.forEach(directive => {
StringMapWrapper.forEach(directive.directive.outputs,
@ -604,8 +588,7 @@ class TemplateParseVisitor implements HtmlAstVisitor {
events.forEach(event => {
if (isPresent(event.target) || !SetWrapper.has(allDirectiveEvents, event.name)) {
this._reportError(
`Event binding ${event.fullName} not emitted by any directive on an embedded template`,
event.sourceSpan);
`Event binding ${event.fullName} not emitted by any directive on an embedded template in ${sourceInfo}`);
}
});
}
@ -628,20 +611,20 @@ class NonBindableVisitor implements HtmlAstVisitor {
var ngContentIndex = component.findNgContentIndex(selector);
var children = htmlVisitAll(this, ast.children, EMPTY_COMPONENT);
return new ElementAst(ast.name, htmlVisitAll(this, ast.attrs), [], [], [], [], children,
ngContentIndex, ast.sourceSpan);
ngContentIndex, ast.sourceInfo);
}
visitAttr(ast: HtmlAttrAst, context: any): AttrAst {
return new AttrAst(ast.name, ast.value, ast.sourceSpan);
return new AttrAst(ast.name, ast.value, ast.sourceInfo);
}
visitText(ast: HtmlTextAst, component: Component): TextAst {
var ngContentIndex = component.findNgContentIndex(TEXT_CSS_SELECTOR);
return new TextAst(ast.value, ngContentIndex, ast.sourceSpan);
return new TextAst(ast.value, ngContentIndex, ast.sourceInfo);
}
}
class BoundElementOrDirectiveProperty {
constructor(public name: string, public expression: AST, public isLiteral: boolean,
public sourceSpan: ParseSourceSpan) {}
public sourceInfo: string) {}
}
export function splitClasses(classAttrValue: string): string[] {

View File

@ -380,7 +380,7 @@ export function main() {
run(rootComp, [dir], 1)
.then((data) => {
expect(data[0][2])
.toEqual(['someVar', 'someValue', 'someEmptyVar', '$implicit']);
.toEqual(['someEmptyVar', '$implicit', 'someVar', 'someValue']);
async.done();
});
}));

View File

@ -1,523 +0,0 @@
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from '../../test_lib';
import {BaseException} from '../../src/facade/exceptions';
import {tokenizeHtml, HtmlToken, HtmlTokenType} from '../../src/compiler/html_lexer';
import {ParseSourceSpan, ParseLocation} from '../../src/compiler/parse_util';
export function main() {
describe('HtmlLexer', () => {
describe('line/column numbers', () => {
it('should work without newlines', () => {
expect(tokenizeAndHumanizeLineColumn('<t>a</t>'))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, '0:0'],
[HtmlTokenType.TAG_OPEN_END, '0:2'],
[HtmlTokenType.TEXT, '0:3'],
[HtmlTokenType.TAG_CLOSE, '0:4'],
[HtmlTokenType.EOF, '0:8']
]);
});
it('should work with one newline', () => {
expect(tokenizeAndHumanizeLineColumn('<t>\na</t>'))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, '0:0'],
[HtmlTokenType.TAG_OPEN_END, '0:2'],
[HtmlTokenType.TEXT, '0:3'],
[HtmlTokenType.TAG_CLOSE, '1:1'],
[HtmlTokenType.EOF, '1:5']
]);
});
it('should work with multiple newlines', () => {
expect(tokenizeAndHumanizeLineColumn('<t\n>\na</t>'))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, '0:0'],
[HtmlTokenType.TAG_OPEN_END, '1:0'],
[HtmlTokenType.TEXT, '1:1'],
[HtmlTokenType.TAG_CLOSE, '2:1'],
[HtmlTokenType.EOF, '2:5']
]);
});
});
describe('comments', () => {
it('should parse comments', () => {
expect(tokenizeAndHumanizeParts('<!--test-->'))
.toEqual([
[HtmlTokenType.COMMENT_START],
[HtmlTokenType.RAW_TEXT, 'test'],
[HtmlTokenType.COMMENT_END],
[HtmlTokenType.EOF]
]);
});
it('should store the locations', () => {expect(tokenizeAndHumanizeSourceSpans('<!--test-->'))
.toEqual([
[HtmlTokenType.COMMENT_START, '<!--'],
[HtmlTokenType.RAW_TEXT, 'test'],
[HtmlTokenType.COMMENT_END, '-->'],
[HtmlTokenType.EOF, '']
])});
it('should report <!- without -', () => {
expect(tokenizeAndHumanizeErrors('<!-a'))
.toEqual([[HtmlTokenType.COMMENT_START, 'Unexpected character "a"', '0:3']]);
});
it('should report missing end comment', () => {
expect(tokenizeAndHumanizeErrors('<!--'))
.toEqual([[HtmlTokenType.RAW_TEXT, 'Unexpected character "EOF"', '0:4']]);
});
});
describe('doctype', () => {
it('should parse doctypes', () => {
expect(tokenizeAndHumanizeParts('<!doctype html>'))
.toEqual([[HtmlTokenType.DOC_TYPE, 'doctype html'], [HtmlTokenType.EOF]]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans('<!doctype html>'))
.toEqual([[HtmlTokenType.DOC_TYPE, '<!doctype html>'], [HtmlTokenType.EOF, '']]);
});
it('should report missing end doctype', () => {
expect(tokenizeAndHumanizeErrors('<!'))
.toEqual([[HtmlTokenType.DOC_TYPE, 'Unexpected character "EOF"', '0:2']]);
});
});
describe('cdata', () => {
it('should parse cdata', () => {
expect(tokenizeAndHumanizeParts('<![cdata[test]]>'))
.toEqual([
[HtmlTokenType.CDATA_START],
[HtmlTokenType.RAW_TEXT, 'test'],
[HtmlTokenType.CDATA_END],
[HtmlTokenType.EOF]
]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans('<![cdata[test]]>'))
.toEqual([
[HtmlTokenType.CDATA_START, '<![cdata['],
[HtmlTokenType.RAW_TEXT, 'test'],
[HtmlTokenType.CDATA_END, ']]>'],
[HtmlTokenType.EOF, '']
]);
});
it('should report <![ without cdata[', () => {
expect(tokenizeAndHumanizeErrors('<![a'))
.toEqual([[HtmlTokenType.CDATA_START, 'Unexpected character "a"', '0:3']]);
});
it('should report missing end cdata', () => {
expect(tokenizeAndHumanizeErrors('<![cdata['))
.toEqual([[HtmlTokenType.RAW_TEXT, 'Unexpected character "EOF"', '0:9']]);
});
});
describe('open tags', () => {
it('should parse open tags without prefix', () => {
expect(tokenizeAndHumanizeParts('<test>'))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 'test'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.EOF]
]);
});
it('should parse namespace prefix', () => {
expect(tokenizeAndHumanizeParts('<ns1:test>'))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, 'ns1', 'test'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.EOF]
]);
});
it('should parse void tags', () => {
expect(tokenizeAndHumanizeParts('<test/>'))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 'test'],
[HtmlTokenType.TAG_OPEN_END_VOID],
[HtmlTokenType.EOF]
]);
});
it('should allow whitespace', () => {
expect(tokenizeAndHumanizeParts('< test >'))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 'test'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.EOF]
]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans('<test>'))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, '<test'],
[HtmlTokenType.TAG_OPEN_END, '>'],
[HtmlTokenType.EOF, '']
]);
});
it('should report missing name after <', () => {
expect(tokenizeAndHumanizeErrors('<'))
.toEqual([[HtmlTokenType.TAG_OPEN_START, 'Unexpected character "EOF"', '0:1']]);
});
it('should report missing >', () => {
expect(tokenizeAndHumanizeErrors('<name'))
.toEqual([[HtmlTokenType.TAG_OPEN_START, 'Unexpected character "EOF"', '0:5']]);
});
});
describe('attributes', () => {
it('should parse attributes without prefix', () => {
expect(tokenizeAndHumanizeParts('<t a>'))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 't'],
[HtmlTokenType.ATTR_NAME, null, 'a'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.EOF]
]);
});
it('should parse attributes with prefix', () => {
expect(tokenizeAndHumanizeParts('<t ns1:a>'))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 't'],
[HtmlTokenType.ATTR_NAME, 'ns1', 'a'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.EOF]
]);
});
it('should parse attributes whose prefix is not valid', () => {
expect(tokenizeAndHumanizeParts('<t (ns1:a)>'))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 't'],
[HtmlTokenType.ATTR_NAME, null, '(ns1:a)'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.EOF]
]);
});
it('should parse attributes with single quote value', () => {
expect(tokenizeAndHumanizeParts("<t a='b'>"))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 't'],
[HtmlTokenType.ATTR_NAME, null, 'a'],
[HtmlTokenType.ATTR_VALUE, 'b'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.EOF]
]);
});
it('should parse attributes with double quote value', () => {
expect(tokenizeAndHumanizeParts('<t a="b">'))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 't'],
[HtmlTokenType.ATTR_NAME, null, 'a'],
[HtmlTokenType.ATTR_VALUE, 'b'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.EOF]
]);
});
it('should parse attributes with unquoted value', () => {
expect(tokenizeAndHumanizeParts('<t a=b>'))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 't'],
[HtmlTokenType.ATTR_NAME, null, 'a'],
[HtmlTokenType.ATTR_VALUE, 'b'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.EOF]
]);
});
it('should allow whitespace', () => {
expect(tokenizeAndHumanizeParts('<t a = b >'))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 't'],
[HtmlTokenType.ATTR_NAME, null, 'a'],
[HtmlTokenType.ATTR_VALUE, 'b'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.EOF]
]);
});
it('should parse attributes with entities in values', () => {
expect(tokenizeAndHumanizeParts('<t a="&#65;">'))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 't'],
[HtmlTokenType.ATTR_NAME, null, 'a'],
[HtmlTokenType.ATTR_VALUE, 'A'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.EOF]
]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans('<t a=b>'))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, '<t'],
[HtmlTokenType.ATTR_NAME, 'a'],
[HtmlTokenType.ATTR_VALUE, 'b'],
[HtmlTokenType.TAG_OPEN_END, '>'],
[HtmlTokenType.EOF, '']
]);
});
it('should report missing value after =', () => {
expect(tokenizeAndHumanizeErrors('<name a='))
.toEqual([[HtmlTokenType.ATTR_VALUE, 'Unexpected character "EOF"', '0:8']]);
});
it('should report missing end quote for \'', () => {
expect(tokenizeAndHumanizeErrors('<name a=\''))
.toEqual([[HtmlTokenType.ATTR_VALUE, 'Unexpected character "EOF"', '0:9']]);
});
it('should report missing end quote for "', () => {
expect(tokenizeAndHumanizeErrors('<name a="'))
.toEqual([[HtmlTokenType.ATTR_VALUE, 'Unexpected character "EOF"', '0:9']]);
});
});
describe('closing tags', () => {
it('should parse closing tags without prefix', () => {
expect(tokenizeAndHumanizeParts('</test>'))
.toEqual([[HtmlTokenType.TAG_CLOSE, null, 'test'], [HtmlTokenType.EOF]]);
});
it('should parse closing tags with prefix', () => {
expect(tokenizeAndHumanizeParts('</ns1:test>'))
.toEqual([[HtmlTokenType.TAG_CLOSE, 'ns1', 'test'], [HtmlTokenType.EOF]]);
});
it('should allow whitespace', () => {
expect(tokenizeAndHumanizeParts('</ test >'))
.toEqual([[HtmlTokenType.TAG_CLOSE, null, 'test'], [HtmlTokenType.EOF]]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans('</test>'))
.toEqual([[HtmlTokenType.TAG_CLOSE, '</test>'], [HtmlTokenType.EOF, '']]);
});
it('should report missing name after </', () => {
expect(tokenizeAndHumanizeErrors('</'))
.toEqual([[HtmlTokenType.TAG_CLOSE, 'Unexpected character "EOF"', '0:2']]);
});
it('should report missing >', () => {
expect(tokenizeAndHumanizeErrors('</test'))
.toEqual([[HtmlTokenType.TAG_CLOSE, 'Unexpected character "EOF"', '0:6']]);
});
});
describe('entities', () => {
it('should parse named entities', () => {
expect(tokenizeAndHumanizeParts('a&amp;b'))
.toEqual([[HtmlTokenType.TEXT, 'a&b'], [HtmlTokenType.EOF]]);
});
it('should parse hexadecimal entities', () => {
expect(tokenizeAndHumanizeParts('&#x41;'))
.toEqual([[HtmlTokenType.TEXT, 'A'], [HtmlTokenType.EOF]]);
});
it('should parse decimal entities', () => {
expect(tokenizeAndHumanizeParts('&#65;'))
.toEqual([[HtmlTokenType.TEXT, 'A'], [HtmlTokenType.EOF]]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans('a&amp;b'))
.toEqual([[HtmlTokenType.TEXT, 'a&amp;b'], [HtmlTokenType.EOF, '']]);
});
it('should report unknown named entities >', () => {
expect(tokenizeAndHumanizeErrors('&tbo;'))
.toEqual([[HtmlTokenType.TEXT, 'Unknown entity "tbo"', '0:0']]);
expect(tokenizeAndHumanizeErrors('&#asdf;'))
.toEqual([[HtmlTokenType.TEXT, 'Unknown entity "#asdf"', '0:0']]);
expect(tokenizeAndHumanizeErrors('&#xasdf;'))
.toEqual([[HtmlTokenType.TEXT, 'Unknown entity "#xasdf"', '0:0']]);
});
});
describe('regular text', () => {
it('should parse text', () => {
expect(tokenizeAndHumanizeParts('a'))
.toEqual([[HtmlTokenType.TEXT, 'a'], [HtmlTokenType.EOF]]);
});
it('should parse entities', () => {
expect(tokenizeAndHumanizeParts('a&amp;b'))
.toEqual([[HtmlTokenType.TEXT, 'a&b'], [HtmlTokenType.EOF]]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans('a'))
.toEqual([[HtmlTokenType.TEXT, 'a'], [HtmlTokenType.EOF, '']]);
});
});
describe('raw text', () => {
it('should parse text', () => {
expect(tokenizeAndHumanizeParts(`<script>a</script>`))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 'script'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.RAW_TEXT, 'a'],
[HtmlTokenType.TAG_CLOSE, null, 'script'],
[HtmlTokenType.EOF]
]);
});
it('should not detect entities', () => {
expect(tokenizeAndHumanizeParts(`<script>&amp;</script>`))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 'script'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.RAW_TEXT, '&amp;'],
[HtmlTokenType.TAG_CLOSE, null, 'script'],
[HtmlTokenType.EOF]
]);
});
it('should ignore other opening tags', () => {
expect(tokenizeAndHumanizeParts(`<script>a<div></script>`))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 'script'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.RAW_TEXT, 'a<div>'],
[HtmlTokenType.TAG_CLOSE, null, 'script'],
[HtmlTokenType.EOF]
]);
});
it('should ignore other closing tags', () => {
expect(tokenizeAndHumanizeParts(`<script>a</test></script>`))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 'script'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.RAW_TEXT, 'a</test>'],
[HtmlTokenType.TAG_CLOSE, null, 'script'],
[HtmlTokenType.EOF]
]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans(`<script>a</script>`))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, '<script'],
[HtmlTokenType.TAG_OPEN_END, '>'],
[HtmlTokenType.RAW_TEXT, 'a'],
[HtmlTokenType.TAG_CLOSE, '</script>'],
[HtmlTokenType.EOF, '']
]);
});
});
describe('escapable raw text', () => {
it('should parse text', () => {
expect(tokenizeAndHumanizeParts(`<title>a</title>`))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 'title'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a'],
[HtmlTokenType.TAG_CLOSE, null, 'title'],
[HtmlTokenType.EOF]
]);
});
it('should detect entities', () => {
expect(tokenizeAndHumanizeParts(`<title>&amp;</title>`))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 'title'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.ESCAPABLE_RAW_TEXT, '&'],
[HtmlTokenType.TAG_CLOSE, null, 'title'],
[HtmlTokenType.EOF]
]);
});
it('should ignore other opening tags', () => {
expect(tokenizeAndHumanizeParts(`<title>a<div></title>`))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 'title'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a<div>'],
[HtmlTokenType.TAG_CLOSE, null, 'title'],
[HtmlTokenType.EOF]
]);
});
it('should ignore other closing tags', () => {
expect(tokenizeAndHumanizeParts(`<title>a</test></title>`))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, null, 'title'],
[HtmlTokenType.TAG_OPEN_END],
[HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a</test>'],
[HtmlTokenType.TAG_CLOSE, null, 'title'],
[HtmlTokenType.EOF]
]);
});
it('should store the locations', () => {
expect(tokenizeAndHumanizeSourceSpans(`<title>a</title>`))
.toEqual([
[HtmlTokenType.TAG_OPEN_START, '<title'],
[HtmlTokenType.TAG_OPEN_END, '>'],
[HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a'],
[HtmlTokenType.TAG_CLOSE, '</title>'],
[HtmlTokenType.EOF, '']
]);
});
});
});
}
function tokenizeWithoutErrors(input: string): HtmlToken[] {
var tokenizeResult = tokenizeHtml(input, 'someUrl');
if (tokenizeResult.errors.length > 0) {
var errorString = tokenizeResult.errors.join('\n');
throw new BaseException(`Unexpected parse errors:\n${errorString}`);
}
return tokenizeResult.tokens;
}
function tokenizeAndHumanizeParts(input: string): any[] {
return tokenizeWithoutErrors(input).map(token => [<any>token.type].concat(token.parts));
}
function tokenizeAndHumanizeSourceSpans(input: string): any[] {
return tokenizeWithoutErrors(input).map(token => [<any>token.type, token.sourceSpan.toString()]);
}
function humanizeLineColumn(location: ParseLocation): string {
return `${location.line}:${location.col}`;
}
function tokenizeAndHumanizeLineColumn(input: string): any[] {
return tokenizeWithoutErrors(input)
.map(token => [<any>token.type, humanizeLineColumn(token.sourceSpan.start)]);
}
function tokenizeAndHumanizeErrors(input: string): any[] {
return tokenizeHtml(input, 'someUrl')
.errors.map(
tokenError =>
[<any>tokenError.tokenType, tokenError.msg, humanizeLineColumn(tokenError.location)]);
}

View File

@ -9,8 +9,7 @@ import {
afterEach
} from 'angular2/testing_internal';
import {HtmlParser, HtmlParseTreeResult} from 'angular2/src/compiler/html_parser';
import {HtmlParser} from 'angular2/src/compiler/html_parser';
import {
HtmlAst,
HtmlAstVisitor,
@ -21,106 +20,129 @@ import {
} from 'angular2/src/compiler/html_ast';
export function main() {
describe('HtmlParser', () => {
describe('DomParser', () => {
var parser: HtmlParser;
beforeEach(() => { parser = new HtmlParser(); });
// TODO: add more test cases
// TODO: separate tests for source spans from tests for tree parsing
// TODO: find a better way to assert the tree structure!
// -> maybe with arrays and object hashes!!
describe('parse', () => {
describe('text nodes', () => {
it('should parse root level text nodes', () => {
expect(humanizeDom(parser.parse('a', 'TestComp'))).toEqual([[HtmlTextAst, 'a']]);
expect(humanizeDom(parser.parse('a', 'TestComp')))
.toEqual([[HtmlTextAst, 'a', 'TestComp > #text(a):nth-child(0)']]);
});
it('should parse text nodes inside regular elements', () => {
expect(humanizeDom(parser.parse('<div>a</div>', 'TestComp')))
.toEqual([[HtmlElementAst, 'div'], [HtmlTextAst, 'a']]);
.toEqual([
[HtmlElementAst, 'div', 'TestComp > div:nth-child(0)'],
[HtmlTextAst, 'a', 'TestComp > div:nth-child(0) > #text(a):nth-child(0)']
]);
});
it('should parse text nodes inside template elements', () => {
expect(humanizeDom(parser.parse('<template>a</template>', 'TestComp')))
.toEqual([[HtmlElementAst, 'template'], [HtmlTextAst, 'a']]);
.toEqual([
[HtmlElementAst, 'template', 'TestComp > template:nth-child(0)'],
[HtmlTextAst, 'a', 'TestComp > template:nth-child(0) > #text(a):nth-child(0)']
]);
});
});
describe('elements', () => {
it('should parse root level elements', () => {
expect(humanizeDom(parser.parse('<div></div>', 'TestComp')))
.toEqual([[HtmlElementAst, 'div']]);
.toEqual([[HtmlElementAst, 'div', 'TestComp > div:nth-child(0)']]);
});
it('should parse elements inside of regular elements', () => {
expect(humanizeDom(parser.parse('<div><span></span></div>', 'TestComp')))
.toEqual([[HtmlElementAst, 'div'], [HtmlElementAst, 'span']]);
.toEqual([
[HtmlElementAst, 'div', 'TestComp > div:nth-child(0)'],
[HtmlElementAst, 'span', 'TestComp > div:nth-child(0) > span:nth-child(0)']
]);
});
it('should parse elements inside of template elements', () => {
expect(humanizeDom(parser.parse('<template><span></span></template>', 'TestComp')))
.toEqual([[HtmlElementAst, 'template'], [HtmlElementAst, 'span']]);
.toEqual([
[HtmlElementAst, 'template', 'TestComp > template:nth-child(0)'],
[HtmlElementAst, 'span', 'TestComp > template:nth-child(0) > span:nth-child(0)']
]);
});
});
describe('attributes', () => {
it('should parse attributes on regular elements', () => {
expect(humanizeDom(parser.parse('<div kEy="v" key2=v2></div>', 'TestComp')))
expect(humanizeDom(parser.parse('<div k="v"></div>', 'TestComp')))
.toEqual([
[HtmlElementAst, 'div'],
[HtmlAttrAst, 'kEy', 'v'],
[HtmlAttrAst, 'key2', 'v2'],
[HtmlElementAst, 'div', 'TestComp > div:nth-child(0)'],
[HtmlAttrAst, 'k', 'v', 'TestComp > div:nth-child(0)[k=v]']
]);
});
it('should parse attributes without values', () => {
expect(humanizeDom(parser.parse('<div k></div>', 'TestComp')))
.toEqual([[HtmlElementAst, 'div'], [HtmlAttrAst, 'k', '']]);
});
it('should parse attributes on svg elements case sensitive', () => {
expect(humanizeDom(parser.parse('<svg viewBox="0"></svg>', 'TestComp')))
.toEqual([[HtmlElementAst, '@svg:svg'], [HtmlAttrAst, 'viewBox', '0']]);
.toEqual([
[HtmlElementAst, 'svg', 'TestComp > svg:nth-child(0)'],
[HtmlAttrAst, 'viewBox', '0', 'TestComp > svg:nth-child(0)[viewBox=0]']
]);
});
it('should parse attributes on template elements', () => {
expect(humanizeDom(parser.parse('<template k="v"></template>', 'TestComp')))
.toEqual([[HtmlElementAst, 'template'], [HtmlAttrAst, 'k', 'v']]);
.toEqual([
[HtmlElementAst, 'template', 'TestComp > template:nth-child(0)'],
[HtmlAttrAst, 'k', 'v', 'TestComp > template:nth-child(0)[k=v]']
]);
});
});
});
describe('unparse', () => {
it('should unparse text nodes',
() => { expect(parser.unparse(parser.parse('a', null))).toEqual('a'); });
it('should unparse elements',
() => { expect(parser.unparse(parser.parse('<a></a>', null))).toEqual('<a></a>'); });
it('should unparse attributes', () => {
expect(parser.unparse(parser.parse('<div a b="c"></div>', null)))
.toEqual('<div a="" b="c"></div>');
});
it('should unparse nested elements', () => {
expect(parser.unparse(parser.parse('<div><a></a></div>', null)))
.toEqual('<div><a></a></div>');
});
it('should unparse nested text nodes', () => {
expect(parser.unparse(parser.parse('<div>a</div>', null))).toEqual('<div>a</div>');
});
});
});
}
function humanizeDom(parseResult: HtmlParseTreeResult): any[] {
// TODO: humanize errors as well!
if (parseResult.errors.length > 0) {
throw parseResult.errors;
}
function humanizeDom(asts: HtmlAst[]): any[] {
var humanizer = new Humanizer();
htmlVisitAll(humanizer, parseResult.rootNodes);
htmlVisitAll(humanizer, asts);
return humanizer.result;
}
class Humanizer implements HtmlAstVisitor {
result: any[] = [];
visitElement(ast: HtmlElementAst, context: any): any {
this.result.push([HtmlElementAst, ast.name]);
this.result.push([HtmlElementAst, ast.name, ast.sourceInfo]);
htmlVisitAll(this, ast.attrs);
htmlVisitAll(this, ast.children);
return null;
}
visitAttr(ast: HtmlAttrAst, context: any): any {
this.result.push([HtmlAttrAst, ast.name, ast.value]);
this.result.push([HtmlAttrAst, ast.name, ast.value, ast.sourceInfo]);
return null;
}
visitText(ast: HtmlTextAst, context: any): any {
this.result.push([HtmlTextAst, ast.value]);
this.result.push([HtmlTextAst, ast.value, ast.sourceInfo]);
return null;
}
}

View File

@ -8,7 +8,7 @@ import {
beforeEach,
afterEach,
inject,
beforeEachProviders
beforeEachBindings
} from 'angular2/testing_internal';
import {provide} from 'angular2/src/core/di';
@ -45,12 +45,9 @@ import {Unparser} from '../core/change_detection/parser/unparser';
var expressionUnparser = new Unparser();
// TODO(tbosch): add tests for checking that we
// keep the correct sourceSpans!
export function main() {
describe('TemplateParser', () => {
beforeEachProviders(() => [
beforeEachBindings(() => [
TEST_PROVIDERS,
provide(ElementSchemaRegistry,
{
@ -75,22 +72,29 @@ export function main() {
describe('parse', () => {
describe('nodes without bindings', () => {
it('should parse text nodes',
() => { expect(humanizeTemplateAsts(parse('a', []))).toEqual([[TextAst, 'a']]); });
it('should parse text nodes', () => {
expect(humanizeTemplateAsts(parse('a', [])))
.toEqual([[TextAst, 'a', 'TestComp > #text(a):nth-child(0)']]);
});
it('should parse elements with attributes', () => {
expect(humanizeTemplateAsts(parse('<div a=b>', [])))
.toEqual([[ElementAst, 'div'], [AttrAst, 'a', 'b']]);
.toEqual([
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[AttrAst, 'a', 'b', 'TestComp > div:nth-child(0)[a=b]']
]);
});
});
it('should parse ngContent', () => {
var parsed = parse('<ng-content select="a">', []);
expect(humanizeTemplateAsts(parsed)).toEqual([[NgContentAst]]);
expect(humanizeTemplateAsts(parsed))
.toEqual([[NgContentAst, 'TestComp > ng-content:nth-child(0)']]);
});
it('should parse bound text nodes', () => {
expect(humanizeTemplateAsts(parse('{{a}}', []))).toEqual([[BoundTextAst, '{{ a }}']]);
expect(humanizeTemplateAsts(parse('{{a}}', [])))
.toEqual([[BoundTextAst, '{{ a }}', 'TestComp > #text({{a}}):nth-child(0)']]);
});
describe('bound properties', () => {
@ -98,64 +102,120 @@ export function main() {
it('should parse and camel case bound properties', () => {
expect(humanizeTemplateAsts(parse('<div [some-prop]="v">', [])))
.toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'someProp', 'v', null]
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[
BoundElementPropertyAst,
PropertyBindingType.Property,
'someProp',
'v',
null,
'TestComp > div:nth-child(0)[[some-prop]=v]'
]
]);
});
it('should normalize property names via the element schema', () => {
expect(humanizeTemplateAsts(parse('<div [mapped-attr]="v">', [])))
.toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'mappedProp', 'v', null]
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[
BoundElementPropertyAst,
PropertyBindingType.Property,
'mappedProp',
'v',
null,
'TestComp > div:nth-child(0)[[mapped-attr]=v]'
]
]);
});
it('should parse and camel case bound attributes', () => {
expect(humanizeTemplateAsts(parse('<div [attr.some-attr]="v">', [])))
.toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Attribute, 'someAttr', 'v', null]
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[
BoundElementPropertyAst,
PropertyBindingType.Attribute,
'someAttr',
'v',
null,
'TestComp > div:nth-child(0)[[attr.some-attr]=v]'
]
]);
});
it('should parse and dash case bound classes', () => {
expect(humanizeTemplateAsts(parse('<div [class.some-class]="v">', [])))
.toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Class, 'some-class', 'v', null]
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[
BoundElementPropertyAst,
PropertyBindingType.Class,
'some-class',
'v',
null,
'TestComp > div:nth-child(0)[[class.some-class]=v]'
]
]);
});
it('should parse and camel case bound styles', () => {
expect(humanizeTemplateAsts(parse('<div [style.some-style]="v">', [])))
.toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Style, 'someStyle', 'v', null]
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[
BoundElementPropertyAst,
PropertyBindingType.Style,
'someStyle',
'v',
null,
'TestComp > div:nth-child(0)[[style.some-style]=v]'
]
]);
});
it('should parse bound properties via [...] and not report them as attributes', () => {
expect(humanizeTemplateAsts(parse('<div [prop]="v">', [])))
.toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null]
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[
BoundElementPropertyAst,
PropertyBindingType.Property,
'prop',
'v',
null,
'TestComp > div:nth-child(0)[[prop]=v]'
]
]);
});
it('should parse bound properties via bind- and not report them as attributes', () => {
expect(humanizeTemplateAsts(parse('<div bind-prop="v">', [])))
.toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null]
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[
BoundElementPropertyAst,
PropertyBindingType.Property,
'prop',
'v',
null,
'TestComp > div:nth-child(0)[bind-prop=v]'
]
]);
});
it('should parse bound properties via {{...}} and not report them as attributes', () => {
expect(humanizeTemplateAsts(parse('<div prop="{{v}}">', [])))
.toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'prop', '{{ v }}', null]
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[
BoundElementPropertyAst,
PropertyBindingType.Property,
'prop',
'{{ v }}',
null,
'TestComp > div:nth-child(0)[prop={{v}}]'
]
]);
});
@ -165,22 +225,46 @@ export function main() {
it('should parse bound events with a target', () => {
expect(humanizeTemplateAsts(parse('<div (window:event)="v">', [])))
.toEqual([[ElementAst, 'div'], [BoundEventAst, 'event', 'window', 'v']]);
.toEqual([
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[
BoundEventAst,
'event',
'window',
'v',
'TestComp > div:nth-child(0)[(window:event)=v]'
]
]);
});
it('should parse bound events via (...) and not report them as attributes', () => {
expect(humanizeTemplateAsts(parse('<div (event)="v">', [])))
.toEqual([[ElementAst, 'div'], [BoundEventAst, 'event', null, 'v']]);
.toEqual([
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[BoundEventAst, 'event', null, 'v', 'TestComp > div:nth-child(0)[(event)=v]']
]);
});
it('should camel case event names', () => {
expect(humanizeTemplateAsts(parse('<div (some-event)="v">', [])))
.toEqual([[ElementAst, 'div'], [BoundEventAst, 'someEvent', null, 'v']]);
.toEqual([
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[
BoundEventAst,
'someEvent',
null,
'v',
'TestComp > div:nth-child(0)[(some-event)=v]'
]
]);
});
it('should parse bound events via on- and not report them as attributes', () => {
expect(humanizeTemplateAsts(parse('<div on-event="v">', [])))
.toEqual([[ElementAst, 'div'], [BoundEventAst, 'event', null, 'v']]);
.toEqual([
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[BoundEventAst, 'event', null, 'v', 'TestComp > div:nth-child(0)[on-event=v]']
]);
});
it('should allow events on explicit embedded templates that are emitted by a directive',
@ -192,9 +276,9 @@ export function main() {
});
expect(humanizeTemplateAsts(parse('<template (e)="f"></template>', [dirA])))
.toEqual([
[EmbeddedTemplateAst],
[BoundEventAst, 'e', null, 'f'],
[DirectiveAst, dirA],
[EmbeddedTemplateAst, 'TestComp > template:nth-child(0)'],
[BoundEventAst, 'e', null, 'f', 'TestComp > template:nth-child(0)[(e)=f]'],
[DirectiveAst, dirA, 'TestComp > template:nth-child(0)'],
]);
});
});
@ -204,9 +288,22 @@ export function main() {
() => {
expect(humanizeTemplateAsts(parse('<div [(prop)]="v">', [])))
.toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null],
[BoundEventAst, 'propChange', null, 'v = $event']
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[
BoundElementPropertyAst,
PropertyBindingType.Property,
'prop',
'v',
null,
'TestComp > div:nth-child(0)[[(prop)]=v]'
],
[
BoundEventAst,
'propChange',
null,
'v = $event',
'TestComp > div:nth-child(0)[[(prop)]=v]'
]
]);
});
@ -214,9 +311,22 @@ export function main() {
() => {
expect(humanizeTemplateAsts(parse('<div bindon-prop="v">', [])))
.toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null],
[BoundEventAst, 'propChange', null, 'v = $event']
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[
BoundElementPropertyAst,
PropertyBindingType.Property,
'prop',
'v',
null,
'TestComp > div:nth-child(0)[bindon-prop=v]'
],
[
BoundEventAst,
'propChange',
null,
'v = $event',
'TestComp > div:nth-child(0)[bindon-prop=v]'
]
]);
});
@ -239,14 +349,14 @@ export function main() {
});
expect(humanizeTemplateAsts(parse('<div a c b>', [dirA, dirB, dirC, comp])))
.toEqual([
[ElementAst, 'div'],
[AttrAst, 'a', ''],
[AttrAst, 'c', ''],
[AttrAst, 'b', ''],
[DirectiveAst, comp],
[DirectiveAst, dirA],
[DirectiveAst, dirB],
[DirectiveAst, dirC]
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[AttrAst, 'a', '', 'TestComp > div:nth-child(0)[a=]'],
[AttrAst, 'b', '', 'TestComp > div:nth-child(0)[b=]'],
[AttrAst, 'c', '', 'TestComp > div:nth-child(0)[c=]'],
[DirectiveAst, comp, 'TestComp > div:nth-child(0)'],
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
[DirectiveAst, dirB, 'TestComp > div:nth-child(0)'],
[DirectiveAst, dirC, 'TestComp > div:nth-child(0)']
]);
});
@ -257,9 +367,16 @@ export function main() {
{selector: '[b]', type: new CompileTypeMetadata({name: 'DirB'})});
expect(humanizeTemplateAsts(parse('<div [a]="b">', [dirA, dirB])))
.toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'a', 'b', null],
[DirectiveAst, dirA]
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[
BoundElementPropertyAst,
PropertyBindingType.Property,
'a',
'b',
null,
'TestComp > div:nth-child(0)[[a]=b]'
],
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)']
]);
});
@ -271,9 +388,16 @@ export function main() {
});
expect(humanizeTemplateAsts(parse('<div></div>', [dirA])))
.toEqual([
[ElementAst, 'div'],
[DirectiveAst, dirA],
[BoundElementPropertyAst, PropertyBindingType.Property, 'a', 'expr', null]
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
[
BoundElementPropertyAst,
PropertyBindingType.Property,
'a',
'expr',
null,
'TestComp > div:nth-child(0)'
]
]);
});
@ -284,8 +408,11 @@ export function main() {
host: {'(a)': 'expr'}
});
expect(humanizeTemplateAsts(parse('<div></div>', [dirA])))
.toEqual(
[[ElementAst, 'div'], [DirectiveAst, dirA], [BoundEventAst, 'a', null, 'expr']]);
.toEqual([
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
[BoundEventAst, 'a', null, 'expr', 'TestComp > div:nth-child(0)']
]);
});
it('should parse directive properties', () => {
@ -293,9 +420,14 @@ export function main() {
{selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['aProp']});
expect(humanizeTemplateAsts(parse('<div [a-prop]="expr"></div>', [dirA])))
.toEqual([
[ElementAst, 'div'],
[DirectiveAst, dirA],
[BoundDirectivePropertyAst, 'aProp', 'expr']
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
[
BoundDirectivePropertyAst,
'aProp',
'expr',
'TestComp > div:nth-child(0)[[a-prop]=expr]'
]
]);
});
@ -304,9 +436,9 @@ export function main() {
{selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['b:a']});
expect(humanizeTemplateAsts(parse('<div [a]="expr"></div>', [dirA])))
.toEqual([
[ElementAst, 'div'],
[DirectiveAst, dirA],
[BoundDirectivePropertyAst, 'b', 'expr']
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
[BoundDirectivePropertyAst, 'b', 'expr', 'TestComp > div:nth-child(0)[[a]=expr]']
]);
});
@ -315,10 +447,15 @@ export function main() {
{selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['a']});
expect(humanizeTemplateAsts(parse('<div a="literal"></div>', [dirA])))
.toEqual([
[ElementAst, 'div'],
[AttrAst, 'a', 'literal'],
[DirectiveAst, dirA],
[BoundDirectivePropertyAst, 'a', '"literal"']
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[AttrAst, 'a', 'literal', 'TestComp > div:nth-child(0)[a=literal]'],
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
[
BoundDirectivePropertyAst,
'a',
'"literal"',
'TestComp > div:nth-child(0)[a=literal]'
]
]);
});
@ -327,10 +464,15 @@ export function main() {
{selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['a']});
expect(humanizeTemplateAsts(parse('<div a="literal" [a]="\'literal2\'"></div>', [dirA])))
.toEqual([
[ElementAst, 'div'],
[AttrAst, 'a', 'literal'],
[DirectiveAst, dirA],
[BoundDirectivePropertyAst, 'a', '"literal2"']
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[AttrAst, 'a', 'literal', 'TestComp > div:nth-child(0)[a=literal]'],
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
[
BoundDirectivePropertyAst,
'a',
'"literal2"',
'TestComp > div:nth-child(0)[[a]=\'literal2\']'
]
]);
});
@ -338,7 +480,10 @@ export function main() {
var dirA = CompileDirectiveMetadata.create(
{selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['a']});
expect(humanizeTemplateAsts(parse('<div></div>', [dirA])))
.toEqual([[ElementAst, 'div'], [DirectiveAst, dirA]]);
.toEqual([
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)']
]);
});
});
@ -347,22 +492,34 @@ export function main() {
it('should parse variables via #... and not report them as attributes', () => {
expect(humanizeTemplateAsts(parse('<div #a>', [])))
.toEqual([[ElementAst, 'div'], [VariableAst, 'a', '']]);
.toEqual([
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[VariableAst, 'a', '', 'TestComp > div:nth-child(0)[#a=]']
]);
});
it('should parse variables via var-... and not report them as attributes', () => {
expect(humanizeTemplateAsts(parse('<div var-a>', [])))
.toEqual([[ElementAst, 'div'], [VariableAst, 'a', '']]);
.toEqual([
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[VariableAst, 'a', '', 'TestComp > div:nth-child(0)[var-a=]']
]);
});
it('should camel case variables', () => {
expect(humanizeTemplateAsts(parse('<div var-some-a>', [])))
.toEqual([[ElementAst, 'div'], [VariableAst, 'someA', '']]);
.toEqual([
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[VariableAst, 'someA', '', 'TestComp > div:nth-child(0)[var-some-a=]']
]);
});
it('should assign variables with empty value to the element', () => {
expect(humanizeTemplateAsts(parse('<div #a></div>', [])))
.toEqual([[ElementAst, 'div'], [VariableAst, 'a', '']]);
.toEqual([
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[VariableAst, 'a', '', 'TestComp > div:nth-child(0)[#a=]']
]);
});
it('should assign variables to directives via exportAs', () => {
@ -370,22 +527,25 @@ export function main() {
{selector: '[a]', type: new CompileTypeMetadata({name: 'DirA'}), exportAs: 'dirA'});
expect(humanizeTemplateAsts(parse('<div a #a="dirA"></div>', [dirA])))
.toEqual([
[ElementAst, 'div'],
[AttrAst, 'a', ''],
[DirectiveAst, dirA],
[VariableAst, 'a', 'dirA']
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[AttrAst, 'a', '', 'TestComp > div:nth-child(0)[a=]'],
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
[VariableAst, 'a', 'dirA', 'TestComp > div:nth-child(0)[#a=dirA]']
]);
});
it('should report variables with values that dont match a directive as errors', () => {
expect(() => parse('<div #a="dirA"></div>', [])).toThrowError(`Template parse errors:
There is no directive with "exportAs" set to "dirA" (<div #a="dirA">): TestComp@0:5`);
There is no directive with "exportAs" set to "dirA" at TestComp > div:nth-child(0)[#a=dirA]`);
});
it('should allow variables with values that dont match a directive on embedded template elements',
() => {
expect(humanizeTemplateAsts(parse('<template #a="b"></template>', [])))
.toEqual([[EmbeddedTemplateAst], [VariableAst, 'a', 'b']]);
.toEqual([
[EmbeddedTemplateAst, 'TestComp > template:nth-child(0)'],
[VariableAst, 'a', 'b', 'TestComp > template:nth-child(0)[#a=b]']
]);
});
it('should assign variables with empty value to components', () => {
@ -398,11 +558,11 @@ There is no directive with "exportAs" set to "dirA" (<div #a="dirA">): TestComp@
});
expect(humanizeTemplateAsts(parse('<div a #a></div>', [dirA])))
.toEqual([
[ElementAst, 'div'],
[AttrAst, 'a', ''],
[VariableAst, 'a', ''],
[DirectiveAst, dirA],
[VariableAst, 'a', '']
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[AttrAst, 'a', '', 'TestComp > div:nth-child(0)[a=]'],
[VariableAst, 'a', '', 'TestComp > div:nth-child(0)[#a=]'],
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
[VariableAst, 'a', '', 'TestComp > div:nth-child(0)[#a=]']
]);
});
@ -411,34 +571,50 @@ There is no directive with "exportAs" set to "dirA" (<div #a="dirA">): TestComp@
describe('explicit templates', () => {
it('should create embedded templates for <template> elements', () => {
expect(humanizeTemplateAsts(parse('<template></template>', [])))
.toEqual([[EmbeddedTemplateAst]]);
.toEqual([[EmbeddedTemplateAst, 'TestComp > template:nth-child(0)']]);
});
});
describe('inline templates', () => {
it('should wrap the element into an EmbeddedTemplateAST', () => {
expect(humanizeTemplateAsts(parse('<div template>', [])))
.toEqual([[EmbeddedTemplateAst], [ElementAst, 'div']]);
.toEqual([
[EmbeddedTemplateAst, 'TestComp > div:nth-child(0)'],
[ElementAst, 'div', 'TestComp > div:nth-child(0)']
]);
});
it('should parse bound properties', () => {
expect(humanizeTemplateAsts(parse('<div template="ngIf test">', [ngIf])))
.toEqual([
[EmbeddedTemplateAst],
[DirectiveAst, ngIf],
[BoundDirectivePropertyAst, 'ngIf', 'test'],
[ElementAst, 'div']
[EmbeddedTemplateAst, 'TestComp > div:nth-child(0)'],
[DirectiveAst, ngIf, 'TestComp > div:nth-child(0)'],
[
BoundDirectivePropertyAst,
'ngIf',
'test',
'TestComp > div:nth-child(0)[template=ngIf test]'
],
[ElementAst, 'div', 'TestComp > div:nth-child(0)']
]);
});
it('should parse variables via #...', () => {
expect(humanizeTemplateAsts(parse('<div template="ngIf #a=b">', [])))
.toEqual([[EmbeddedTemplateAst], [VariableAst, 'a', 'b'], [ElementAst, 'div']]);
.toEqual([
[EmbeddedTemplateAst, 'TestComp > div:nth-child(0)'],
[VariableAst, 'a', 'b', 'TestComp > div:nth-child(0)[template=ngIf #a=b]'],
[ElementAst, 'div', 'TestComp > div:nth-child(0)']
]);
});
it('should parse variables via var ...', () => {
expect(humanizeTemplateAsts(parse('<div template="ngIf var a=b">', [])))
.toEqual([[EmbeddedTemplateAst], [VariableAst, 'a', 'b'], [ElementAst, 'div']]);
.toEqual([
[EmbeddedTemplateAst, 'TestComp > div:nth-child(0)'],
[VariableAst, 'a', 'b', 'TestComp > div:nth-child(0)[template=ngIf var a=b]'],
[ElementAst, 'div', 'TestComp > div:nth-child(0)']
]);
});
describe('directives', () => {
@ -449,12 +625,17 @@ There is no directive with "exportAs" set to "dirA" (<div #a="dirA">): TestComp@
{selector: '[b]', type: new CompileTypeMetadata({name: 'DirB'})});
expect(humanizeTemplateAsts(parse('<div template="a b" b>', [dirA, dirB])))
.toEqual([
[EmbeddedTemplateAst],
[DirectiveAst, dirA],
[BoundDirectivePropertyAst, 'a', 'b'],
[ElementAst, 'div'],
[AttrAst, 'b', ''],
[DirectiveAst, dirB]
[EmbeddedTemplateAst, 'TestComp > div:nth-child(0)'],
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
[
BoundDirectivePropertyAst,
'a',
'b',
'TestComp > div:nth-child(0)[template=a b]'
],
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[AttrAst, 'b', '', 'TestComp > div:nth-child(0)[b=]'],
[DirectiveAst, dirB, 'TestComp > div:nth-child(0)']
]);
});
@ -465,12 +646,12 @@ There is no directive with "exportAs" set to "dirA" (<div #a="dirA">): TestComp@
{selector: '[b]', type: new CompileTypeMetadata({name: 'DirB'})});
expect(humanizeTemplateAsts(parse('<div template="#a=b" b>', [dirA, dirB])))
.toEqual([
[EmbeddedTemplateAst],
[VariableAst, 'a', 'b'],
[DirectiveAst, dirA],
[ElementAst, 'div'],
[AttrAst, 'b', ''],
[DirectiveAst, dirB]
[EmbeddedTemplateAst, 'TestComp > div:nth-child(0)'],
[VariableAst, 'a', 'b', 'TestComp > div:nth-child(0)[template=#a=b]'],
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[AttrAst, 'b', '', 'TestComp > div:nth-child(0)[b=]'],
[DirectiveAst, dirB, 'TestComp > div:nth-child(0)']
]);
});
@ -479,23 +660,30 @@ There is no directive with "exportAs" set to "dirA" (<div #a="dirA">): TestComp@
it('should work with *... and use the attribute name as property binding name', () => {
expect(humanizeTemplateAsts(parse('<div *ng-if="test">', [ngIf])))
.toEqual([
[EmbeddedTemplateAst],
[DirectiveAst, ngIf],
[BoundDirectivePropertyAst, 'ngIf', 'test'],
[ElementAst, 'div']
[EmbeddedTemplateAst, 'TestComp > div:nth-child(0)'],
[DirectiveAst, ngIf, 'TestComp > div:nth-child(0)'],
[
BoundDirectivePropertyAst,
'ngIf',
'test',
'TestComp > div:nth-child(0)[*ng-if=test]'
],
[ElementAst, 'div', 'TestComp > div:nth-child(0)']
]);
});
it('should work with *... and empty value', () => {
expect(humanizeTemplateAsts(parse('<div *ng-if>', [ngIf])))
.toEqual([
[EmbeddedTemplateAst],
[DirectiveAst, ngIf],
[BoundDirectivePropertyAst, 'ngIf', 'null'],
[ElementAst, 'div']
[EmbeddedTemplateAst, 'TestComp > div:nth-child(0)'],
[DirectiveAst, ngIf, 'TestComp > div:nth-child(0)'],
[BoundDirectivePropertyAst, 'ngIf', 'null', 'TestComp > div:nth-child(0)[*ng-if=]'],
[ElementAst, 'div', 'TestComp > div:nth-child(0)']
]);
});
});
});
describe('content projection', () => {
@ -600,14 +788,14 @@ There is no directive with "exportAs" set to "dirA" (<div #a="dirA">): TestComp@
});
describe('error cases', () => {
it('should report invalid property names', () => {
it('should throw on invalid property names', () => {
expect(() => parse('<div [invalid-prop]></div>', [])).toThrowError(`Template parse errors:
Can't bind to 'invalidProp' since it isn't a known native property (<div [invalid-prop]>): TestComp@0:5`);
Can't bind to 'invalidProp' since it isn't a known native property in TestComp > div:nth-child(0)[[invalid-prop]=]`);
});
it('should report errors in expressions', () => {
expect(() => parse('<div [prop]="a b"></div>', [])).toThrowErrorWith(`Template parse errors:
Parser Error: Unexpected token 'b' at column 3 in [a b] in TestComp@0:5 in [prop]="a b": TestComp@0:5`);
Parser Error: Unexpected token 'b' at column 3 in [a b] in TestComp > div:nth-child(0)[[prop]=a b]`);
});
it('should not throw on invalid property names if the property is used by a directive',
@ -633,8 +821,8 @@ Parser Error: Unexpected token 'b' at column 3 in [a b] in TestComp@0:5 in [prop
type: new CompileTypeMetadata({name: 'DirB'}),
template: new CompileTemplateMetadata({ngContentSelectors: []})
});
expect(() => parse('<div/>', [dirB, dirA])).toThrowError(`Template parse errors:
More than one component: DirB,DirA in <div/>: TestComp@0:0`);
expect(() => parse('<div>', [dirB, dirA])).toThrowError(`Template parse errors:
More than one component: DirB,DirA in TestComp > div:nth-child(0)`);
});
it('should not allow components or element bindings nor dom events on explicit embedded templates',
@ -659,20 +847,23 @@ Property binding a not used by any directive on an embedded template in TestComp
type: new CompileTypeMetadata({name: 'DirA'}),
template: new CompileTemplateMetadata({ngContentSelectors: []})
});
expect(() => parse('<div *a="b"></div>', [dirA])).toThrowError(`Template parse errors:
Components on an embedded template: DirA in <div *a="b">: TestComp@0:0
Property binding a not used by any directive on an embedded template in <div *a="b">: TestComp@0:0`);
expect(() => parse('<div *a="b">', [dirA])).toThrowError(`Template parse errors:
Components on an embedded template: DirA in TestComp > div:nth-child(0)
Property binding a not used by any directive on an embedded template in TestComp > div:nth-child(0)[*a=b]`);
});
});
describe('ignore elements', () => {
it('should ignore <script> elements', () => {
expect(humanizeTemplateAsts(parse('<script></script>a', []))).toEqual([[TextAst, 'a']]);
it('should ignore <script> elements but include them for source info', () => {
expect(humanizeTemplateAsts(parse('<script></script>a', [])))
.toEqual([[TextAst, 'a', 'TestComp > #text(a):nth-child(1)']]);
});
it('should ignore <style> elements', () => {
expect(humanizeTemplateAsts(parse('<style></style>a', []))).toEqual([[TextAst, 'a']]);
it('should ignore <style> elements but include them for source info', () => {
expect(humanizeTemplateAsts(parse('<style></style>a', [])))
.toEqual([[TextAst, 'a', 'TestComp > #text(a):nth-child(1)']]);
});
describe('<link rel="stylesheet">', () => {
@ -682,73 +873,108 @@ Property binding a not used by any directive on an embedded template in <div *a=
expect(humanizeTemplateAsts(
parse('<link rel="stylesheet" href="http://someurl"></link>a', [])))
.toEqual([
[ElementAst, 'link'],
[AttrAst, 'href', 'http://someurl'],
[AttrAst, 'rel', 'stylesheet'],
[TextAst, 'a']
[ElementAst, 'link', 'TestComp > link:nth-child(0)'],
[
AttrAst,
'href',
'http://someurl',
'TestComp > link:nth-child(0)[href=http://someurl]'
],
[AttrAst, 'rel', 'stylesheet', 'TestComp > link:nth-child(0)[rel=stylesheet]'],
[TextAst, 'a', 'TestComp > #text(a):nth-child(1)']
]);
});
it('should keep <link rel="stylesheet"> elements if they have no uri', () => {
expect(humanizeTemplateAsts(parse('<link rel="stylesheet"></link>a', [])))
.toEqual([[ElementAst, 'link'], [AttrAst, 'rel', 'stylesheet'], [TextAst, 'a']]);
.toEqual([
[ElementAst, 'link', 'TestComp > link:nth-child(0)'],
[AttrAst, 'rel', 'stylesheet', 'TestComp > link:nth-child(0)[rel=stylesheet]'],
[TextAst, 'a', 'TestComp > #text(a):nth-child(1)']
]);
});
it('should ignore <link rel="stylesheet"> elements if they have a relative uri', () => {
expect(
humanizeTemplateAsts(parse('<link rel="stylesheet" href="./other.css"></link>a', [])))
.toEqual([[TextAst, 'a']]);
.toEqual([[TextAst, 'a', 'TestComp > #text(a):nth-child(1)']]);
});
it('should ignore <link rel="stylesheet"> elements if they have a package: uri', () => {
expect(humanizeTemplateAsts(
parse('<link rel="stylesheet" href="package:somePackage"></link>a', [])))
.toEqual([[TextAst, 'a']]);
.toEqual([[TextAst, 'a', 'TestComp > #text(a):nth-child(1)']]);
});
});
it('should ignore bindings on children of elements with ng-non-bindable', () => {
expect(humanizeTemplateAsts(parse('<div ng-non-bindable>{{b}}</div>', [])))
.toEqual([[ElementAst, 'div'], [AttrAst, 'ng-non-bindable', ''], [TextAst, '{{b}}']]);
.toEqual([
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[AttrAst, 'ng-non-bindable', '', 'TestComp > div:nth-child(0)[ng-non-bindable=]'],
[TextAst, '{{b}}', 'TestComp > div:nth-child(0) > #text({{b}}):nth-child(0)']
]);
});
it('should keep nested children of elements with ng-non-bindable', () => {
expect(humanizeTemplateAsts(parse('<div ng-non-bindable><span>{{b}}</span></div>', [])))
.toEqual([
[ElementAst, 'div'],
[AttrAst, 'ng-non-bindable', ''],
[ElementAst, 'span'],
[TextAst, '{{b}}']
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[AttrAst, 'ng-non-bindable', '', 'TestComp > div:nth-child(0)[ng-non-bindable=]'],
[ElementAst, 'span', 'TestComp > div:nth-child(0) > span:nth-child(0)'],
[
TextAst,
'{{b}}',
'TestComp > div:nth-child(0) > span:nth-child(0) > #text({{b}}):nth-child(0)'
]
]);
});
it('should ignore <script> elements inside of elements with ng-non-bindable', () => {
expect(humanizeTemplateAsts(parse('<div ng-non-bindable><script></script>a</div>', [])))
.toEqual([[ElementAst, 'div'], [AttrAst, 'ng-non-bindable', ''], [TextAst, 'a']]);
});
it('should ignore <script> elements inside of elements with ng-non-bindable but include them for source info',
() => {
expect(humanizeTemplateAsts(parse('<div ng-non-bindable><script></script>a</div>', [])))
.toEqual([
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[AttrAst, 'ng-non-bindable', '', 'TestComp > div:nth-child(0)[ng-non-bindable=]'],
[TextAst, 'a', 'TestComp > div:nth-child(0) > #text(a):nth-child(1)']
]);
});
it('should ignore <style> elements inside of elements with ng-non-bindable', () => {
expect(humanizeTemplateAsts(parse('<div ng-non-bindable><style></style>a</div>', [])))
.toEqual([[ElementAst, 'div'], [AttrAst, 'ng-non-bindable', ''], [TextAst, 'a']]);
});
it('should ignore <style> elements inside of elements with ng-non-bindable but include them for source info',
() => {
expect(humanizeTemplateAsts(parse('<div ng-non-bindable><style></style>a</div>', [])))
.toEqual([
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[AttrAst, 'ng-non-bindable', '', 'TestComp > div:nth-child(0)[ng-non-bindable=]'],
[TextAst, 'a', 'TestComp > div:nth-child(0) > #text(a):nth-child(1)']
]);
});
it('should ignore <link rel="stylesheet"> elements inside of elements with ng-non-bindable',
it('should ignore <link rel="stylesheet"> elements inside of elements with ng-non-bindable but include them for source info',
() => {
expect(humanizeTemplateAsts(
parse('<div ng-non-bindable><link rel="stylesheet"></link>a</div>', [])))
.toEqual([[ElementAst, 'div'], [AttrAst, 'ng-non-bindable', ''], [TextAst, 'a']]);
.toEqual([
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[AttrAst, 'ng-non-bindable', '', 'TestComp > div:nth-child(0)[ng-non-bindable=]'],
[TextAst, 'a', 'TestComp > div:nth-child(0) > #text(a):nth-child(1)']
]);
});
it('should convert <ng-content> elements into regular elements inside of elements with ng-non-bindable',
it('should convert <ng-content> elements into regular elements inside of elements with ng-non-bindable but include them for source info',
() => {
expect(humanizeTemplateAsts(
parse('<div ng-non-bindable><ng-content></ng-content>a</div>', [])))
.toEqual([
[ElementAst, 'div'],
[AttrAst, 'ng-non-bindable', ''],
[ElementAst, 'ng-content'],
[TextAst, 'a']
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
[AttrAst, 'ng-non-bindable', '', 'TestComp > div:nth-child(0)[ng-non-bindable=]'],
[
ElementAst,
'ng-content',
'TestComp > div:nth-child(0) > ng-content:nth-child(0)'
],
[TextAst, 'a', 'TestComp > div:nth-child(0) > #text(a):nth-child(1)']
]);
});
@ -765,11 +991,11 @@ export function humanizeTemplateAsts(templateAsts: TemplateAst[]): any[] {
class TemplateHumanizer implements TemplateAstVisitor {
result: any[] = [];
visitNgContent(ast: NgContentAst, context: any): any {
this.result.push([NgContentAst]);
this.result.push([NgContentAst, ast.sourceInfo]);
return null;
}
visitEmbeddedTemplate(ast: EmbeddedTemplateAst, context: any): any {
this.result.push([EmbeddedTemplateAst]);
this.result.push([EmbeddedTemplateAst, ast.sourceInfo]);
templateVisitAll(this, ast.attrs);
templateVisitAll(this, ast.outputs);
templateVisitAll(this, ast.vars);
@ -778,7 +1004,7 @@ class TemplateHumanizer implements TemplateAstVisitor {
return null;
}
visitElement(ast: ElementAst, context: any): any {
this.result.push([ElementAst, ast.name]);
this.result.push([ElementAst, ast.name, ast.sourceInfo]);
templateVisitAll(this, ast.attrs);
templateVisitAll(this, ast.inputs);
templateVisitAll(this, ast.outputs);
@ -788,12 +1014,17 @@ class TemplateHumanizer implements TemplateAstVisitor {
return null;
}
visitVariable(ast: VariableAst, context: any): any {
this.result.push([VariableAst, ast.name, ast.value]);
this.result.push([VariableAst, ast.name, ast.value, ast.sourceInfo]);
return null;
}
visitEvent(ast: BoundEventAst, context: any): any {
this.result.push(
[BoundEventAst, ast.name, ast.target, expressionUnparser.unparse(ast.handler)]);
this.result.push([
BoundEventAst,
ast.name,
ast.target,
expressionUnparser.unparse(ast.handler),
ast.sourceInfo
]);
return null;
}
visitElementProperty(ast: BoundElementPropertyAst, context: any): any {
@ -802,24 +1033,25 @@ class TemplateHumanizer implements TemplateAstVisitor {
ast.type,
ast.name,
expressionUnparser.unparse(ast.value),
ast.unit
ast.unit,
ast.sourceInfo
]);
return null;
}
visitAttr(ast: AttrAst, context: any): any {
this.result.push([AttrAst, ast.name, ast.value]);
this.result.push([AttrAst, ast.name, ast.value, ast.sourceInfo]);
return null;
}
visitBoundText(ast: BoundTextAst, context: any): any {
this.result.push([BoundTextAst, expressionUnparser.unparse(ast.value)]);
this.result.push([BoundTextAst, expressionUnparser.unparse(ast.value), ast.sourceInfo]);
return null;
}
visitText(ast: TextAst, context: any): any {
this.result.push([TextAst, ast.value]);
this.result.push([TextAst, ast.value, ast.sourceInfo]);
return null;
}
visitDirective(ast: DirectiveAst, context: any): any {
this.result.push([DirectiveAst, ast.directive]);
this.result.push([DirectiveAst, ast.directive, ast.sourceInfo]);
templateVisitAll(this, ast.inputs);
templateVisitAll(this, ast.hostProperties);
templateVisitAll(this, ast.hostEvents);
@ -827,16 +1059,16 @@ class TemplateHumanizer implements TemplateAstVisitor {
return null;
}
visitDirectiveProperty(ast: BoundDirectivePropertyAst, context: any): any {
this.result.push(
[BoundDirectivePropertyAst, ast.directiveName, expressionUnparser.unparse(ast.value)]);
this.result.push([
BoundDirectivePropertyAst,
ast.directiveName,
expressionUnparser.unparse(ast.value),
ast.sourceInfo
]);
return null;
}
}
function sourceInfo(ast: TemplateAst): string {
return `${ast.sourceSpan}: ${ast.sourceSpan.start}`;
}
function humanizeContentProjection(templateAsts: TemplateAst[]): any[] {
var humanizer = new TemplateContentProjectionHumanizer();
templateVisitAll(humanizer, templateAsts);

View File

@ -26,7 +26,7 @@ export function main() {
beforeEach(inject([HtmlParser], (_htmlParser: HtmlParser) => { htmlParser = _htmlParser; }));
function preparse(html: string): PreparsedElement {
return preparseElement(htmlParser.parse(html, '').rootNodes[0]);
return preparseElement(htmlParser.parse(html, '')[0]);
}
it('should detect script elements', inject([HtmlParser], (htmlParser: HtmlParser) => {

View File

@ -577,10 +577,11 @@ export function main() {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async) => {
tcb.overrideView(MyComp, new ViewMetadata({
template: '<p><child-cmp var-alice/><child-cmp var-bob/></p>',
directives: [ChildComp]
}))
tcb.overrideView(
MyComp, new ViewMetadata({
template: '<p><child-cmp var-alice></child-cmp><child-cmp var-bob></p>',
directives: [ChildComp]
}))
.createAsync(MyComp)
.then((fixture) => {
@ -1313,7 +1314,7 @@ export function main() {
tcb =
tcb.overrideView(MyComp, new ViewMetadata({
directives: [DirectiveThrowingAnError],
template: `<directive-throwing-error></directive-throwing-error>`
template: `<directive-throwing-error></<directive-throwing-error>`
}));
PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => {