声明
HTML的解析过程是非常复杂的,下载、解析、脚本执行、显示是交错进行的。而且,HTML的解析器具有非常强的容错能力。
对于初次接触webkit源码的童鞋来说,是无法全面理解的。而且,本文立意也不是介绍HTMl的解析算法一类的东西。即便是我自己,对于很多东西都理解不了。
所以,本文重在解释HTML的解析过程,解说各个组成部分及功能。以后有机会,我将详细分析解析的算法。
解析过程中的重要类和功能
- Document和DocumentParser是相互引用的关系
- HTMLDocumentParser继承自ScriptableDocumentParser,在继承自DecodedDataDocumentParser。本文不讨论脚本相关问题,因此,可以忽略ScriptableDocumentParser。DecodedDataDocumentParser类主要功能就是实现字符解码功能。
- HTMLInputStream:保存解码后的字符流,可以看作一个缓冲区。和标准输入流的作用是一样的;
- HTMLTokenizer : 解析字符流解析,将字符流分解成节点(包括节点名和属性列表),注释、Doc声明、结束节点、文本(节点包含的文字),这些信息都保存在HTMLToken类中。其作用是词法解析器; 实现这个功能的主要函数是nextToken;
- HTMLTreeBuilder:它主要作用是生成DOM树,并对其语义进行检查(参阅processStartTag函数的代码)。如,如果在head标签中包含一个body标签,它就会检查出来,并报告错误。主要函数是constructTreeFromToken;
- HTMLToken:这是一个中间类,由HTMLTokenizer生成,交给HTMLTreeBuilder使用;
- HTMLConstructionSite : 这个类是负责创建HTML元素,并最终完成DOM树组装的函数。例如,它将标签 <img> 生成一个HTMLImageElement对象。 除了一些关键的标签外(如html, body, head等),其他标签的创建,通过HTMLElementFactory来实现; 对于属性的解析,直接调用生成的Element的parserSetAttributes函数,来实现。参阅HTMLConstructionSite::createHTMLElement函数的实现;
- HTMLPreloadScanner : 这是一个负责查找和加载子资源的对象。它通过扫描节点中的 "src" , "link"等属性,找到外部连接资源后,通过CachedResourceLoader进行预加载。CachedResourceLoader是从DocumentLoader中得到的。这一点可以参考前一章。
注意:HTMLElementFactory是通过脚本生成的,在源码中没有定义。
解析过程简要说明(解析中的错误处理不是核心问题,忽略)
说明: 下图中的箭头线表示下个处理单元,并不表示函数调用。箭头线上的文字,表示箭头所指对象,被调用的函数名。
这个过程是
- 当DocumentWriter调用DocumentParser::appendBytes时(实际上是HTMLDocumentParser),首先进行字符集转换,然后,将转换后字符集存入HTMLInputStream中
- 在HTMLDocumentParser::pumpTokenizer函数中,HTMLTokenizer::nextToken函数将字符流解析为HTMLToken对象
- HTMLToken对象将交给HTMLTreeBuilder
- HTMLTreeBuilder分析标签,以确定标签是否是期望的(见代码HTMLTreeBuilder::processToken)
- 调用HTMLConstructionSite的insertHTMLElement, insertHTMLHeadElement, ... 等(根据标签的类型),将他们插入到HTMLConstructionSite中
- HTMLConstructionSite调用HTMLElementFactory::createHTMLElement(当然也不是所有的,有一部分是直接创建的)创建HTMLElement对象
- HTMLElement的parserSetAttributes函数会被调用,用于解析属性
- 当创建了一个元素后,该元素会被加入到当前节点中。HTMLConstructionSite::attachLater函数通过异步完成了该功能。
- HTMLToken对象将交给HTMLPreloadScanner
- HTMLPreloadScanner的scan函数被调用
- 生成一个PreloadTask,放在队列中
- 从队列中取得PreloadTask,调用它的preload函数
- PreloadTask::preload或调用CachedResouceLoader的preload,进行资源的预加载。
- 资源预加载时,是通过资源的URL作为key,被CachedresourceLoader管理起来的,在后面需要时,通过URL来获取这些资源。
- CachedResourceLoader对象是从DocumentLoader中获取的,ProloadTask是通过Document对象找到DocumentLoader的。
- 详细查看代码HTMLPreloadScanner::processToken
HTMLConstructionSite使用了一种称为开发元素栈的方法,来帮助构造,英文是stack of open elements,详细可参阅http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#the-stack-of-open-elements 。对这个算法我也不是很清楚,以后再研究吧。
元素属性的设置
元素属性通过Element::parserSetAttributes函数来设置。
void Element::parserSetAttributes(const Vector<Attribute>& attributeVector, FragmentScriptingPermission scriptingPermission)
{
....
Vector<Attribute> filteredAttributes = attributeVector;
.....
if (document() && document()->sharedObjectPool())
m_attributeData = document()->sharedObjectPool()->cachedImmutableElementAttributeData(filteredAttributes);
else
m_attributeData = ElementAttributeData::createImmutable(filteredAttributes);
// Iterate over the set of attributes we already have on the stack in case
// attributeChanged mutates m_attributeData.
// FIXME: Find a way so we don't have to do this.
for (unsigned i = 0; i < filteredAttributes.size(); ++i)
attributeChanged(filteredAttributes[i].name(), filteredAttributes[i].value());
}
- m_attributeData 这是存储属性的对象。Element元素可以通过setAttribute和getAttribute来访问属性。
- attributeChanged函数调用parseAttribute函数。这个函数由派生类实现。它的作用是:让元素有机会根据属性创建对应的对象。如,对于HTMLImageElement类,它parseAttribute就会处理"src"属性,根据src属性值,加载图片。
资源的加载和获取
HTMLPreloadScanner发现并调用CachedresorceLoader加载资源。
CachedResourceLoader中的资源是通过URL来唯一标识的。当元素的parseAttribute被调用时,元素就会从CachedResourceLoader中取得需要的资源。
以HTMLImageElement为例。
HTMLImageElement的parseAttribute函数代码
void HTMLImageElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
if (name == altAttr) {
....
} else if (name == srcAttr) {
m_imageLoader.updateFromElementIgnoringPreviousError();
....
} else if (name ....
} else
HTMLElement::parseAttribute(name, value);
}
注意语句
m_imageLoader.updateFromElementIgnoringPreviousError()。m_imageLoader是一个HTMLImageLoader(继承自ImageLoader)对象,这个对象是负责从CachedResourceLoader中加载图片的。
ImageLoader::updateFromElementIgnoringPreviousError()调用了ImageLoader::updateFromElement函数,我们看看这个函数的实现
void ImageLoader::updateFromElement()
{
....
//重要:获取 src属性的值
AtomicString attr = client()->sourceElement()->getAttribute(client()->sourceElement()->imageSourceAttributeName());
...
// Do not load any image if the 'src' attribute is missing or if it is
// an empty string.
CachedResourceHandle<CachedImage> newImage = 0;
if (!attr.isNull() && !stripLeadingAndTrailingHTMLSpaces(attr).isEmpty()) {
//重要:根据url(attr的值),创建一个request,通过该request获取图片
CachedResourceRequest request(ResourceRequest(document()->completeURL(sourceURI(attr))));
request.setInitiator(client()->sourceElement());
.....
if (m_loadManually) {
bool autoLoadOtherImages = document()->cachedResourceLoader()->autoLoadImages();
document()->cachedResourceLoader()->setAutoLoadImages(false);
newImage = new CachedImage(request.resourceRequest()); //创建image对象
newImage->setLoading(true);
newImage->setOwningCachedResourceLoader(document()->cachedResourceLoader());
document()->cachedResourceLoader()->m_documentResources.set(newImage->url(), newImage.get());
document()->cachedResourceLoader()->setAutoLoadImages(autoLoadOtherImages);
} else
newImage = document()->cachedResourceLoader()->requestImage(request); //直接获取一个cached的image对象
....
}从 src属性中取得url,然后根据url,从document()->cachedResourceLoader (实际上就是DocumentLoader的cachedResourceLoader对象)中得到对应的图片。
本文介绍了WebKit内核中HTML的解析过程,涉及DocumentParser、HTMLTokenizer、HTMLTreeBuilder等关键组件的作用。HTMLTokenizer负责词法解析,HTMLTreeBuilder生成DOM树并检查语义。HTMLConstructionSite创建HTML元素,HTMLPreloadScanner则负责预加载子资源。解析过程中,元素属性通过Element::parserSetAttributes设置,资源通过CachedResourceLoader加载和管理。
3万+

被折叠的 条评论
为什么被折叠?



