From d5257a2ae3b297c0c4fbd2565cafd08646740650 Mon Sep 17 00:00:00 2001 From: "terry@google.com" Date: Mon, 13 Jan 2014 17:21:47 +0000 Subject: [PATCH] Removed obsolete code BUG= R=vsm@google.com Review URL: https://codereview.chromium.org//137013002 git-svn-id: https://dart.googlecode.com/svn/branches/bleeding_edge/dart@31747 260f80e4-7a28-3924-810f-c04153c831b5 --- utils/css/css | 25 - utils/css/css.dart | 72 - utils/css/css.html | 8 - utils/css/cssoptions.dart | 93 -- utils/css/cssselectorexception.dart | 23 - utils/css/cssworld.dart | 26 - utils/css/generate.dart | 92 -- utils/css/parser.dart | 1017 ------------- utils/css/source.dart | 186 --- utils/css/token.dart | 60 - utils/css/tokenizer.dart | 315 ---- utils/css/tokenizer_base.dart | 454 ------ utils/css/tokenkind.dart | 596 -------- utils/css/tool.dart | 84 -- utils/css/tree.dart | 1279 ----------------- utils/css/treebase.dart | 124 -- utils/css/uitest.dart | 191 --- utils/css/validate.dart | 113 -- utils/css/world.dart | 170 --- utils/lib/file_system.dart | 75 - utils/lib/file_system_memory.dart | 40 - utils/lib/file_system_vm.dart | 42 - utils/template/codegen.dart | 1013 ------------- utils/template/htmltree.dart | 425 ------ utils/template/parser.dart | 720 ---------- utils/template/source.dart | 186 --- utils/template/template | 78 - utils/template/template.dart | 47 - utils/template/template.html | 11 - utils/template/template_tool.html | 11 - utils/template/temploptions.dart | 93 -- utils/template/token.dart | 60 - utils/template/tokenizer.dart | 311 ---- utils/template/tokenizer_base.dart | 465 ------ utils/template/tokenkind.dart | 465 ------ utils/template/tool.dart | 107 -- utils/template/tree.dart | 105 -- utils/template/uitest.dart | 573 -------- utils/template/utils.dart | 55 - utils/template/world.dart | 169 --- utils/tests/css/css.status | 21 - utils/tests/css/declaration_test.dart | 249 ---- utils/tests/css/expression_test.dart | 524 ------- utils/tests/css/selector_literal_test.dart | 235 --- utils/tests/template/README.txt | 58 - utils/tests/template/applications.tmpl | 12 - utils/tests/template/applications2.tmpl | 10 - utils/tests/template/callview.tmpl | 18 - utils/tests/template/complex_datamodel.dart | 122 -- utils/tests/template/name_entry.tmpl | 8 - utils/tests/template/name_entry2.tmpl | 14 - utils/tests/template/name_entry_css.tmpl | 1 - utils/tests/template/name_entry_simple.tmpl | 16 - utils/tests/template/name_entry_text.tmpl | 5 - utils/tests/template/nestedview.tmpl | 27 - utils/tests/template/productview.tmpl | 12 - utils/tests/template/productview2.tmpl | 16 - utils/tests/template/productview3.tmpl | 10 - .../tests/template/productview_localname.tmpl | 12 - utils/tests/template/real_app.dart | 108 -- utils/tests/template/realviews.tmpl | 106 -- utils/tests/template/run | 135 -- utils/tests/template/sample.dart | 243 ---- utils/tests/template/test_complex.dart | 17 - utils/tests/template/test_complex2.dart | 16 - utils/tests/template/test_list.dart | 25 - utils/tests/template/test_nested.dart | 25 - utils/tests/template/test_simple.dart | 16 - utils/tests/template/test_with.dart | 23 - utils/tests/template/top_searches.tmpl | 18 - utils/tests/template/top_searches2.tmpl | 64 - utils/tests/template/top_searches_css.tmpl | 49 - 72 files changed, 12194 deletions(-) delete mode 100755 utils/css/css delete mode 100644 utils/css/css.dart delete mode 100755 utils/css/css.html delete mode 100644 utils/css/cssoptions.dart delete mode 100644 utils/css/cssselectorexception.dart delete mode 100644 utils/css/cssworld.dart delete mode 100644 utils/css/generate.dart delete mode 100644 utils/css/parser.dart delete mode 100644 utils/css/source.dart delete mode 100644 utils/css/token.dart delete mode 100644 utils/css/tokenizer.dart delete mode 100644 utils/css/tokenizer_base.dart delete mode 100644 utils/css/tokenkind.dart delete mode 100644 utils/css/tool.dart delete mode 100644 utils/css/tree.dart delete mode 100644 utils/css/treebase.dart delete mode 100644 utils/css/uitest.dart delete mode 100644 utils/css/validate.dart delete mode 100644 utils/css/world.dart delete mode 100644 utils/lib/file_system.dart delete mode 100644 utils/lib/file_system_memory.dart delete mode 100644 utils/lib/file_system_vm.dart delete mode 100644 utils/template/codegen.dart delete mode 100644 utils/template/htmltree.dart delete mode 100644 utils/template/parser.dart delete mode 100644 utils/template/source.dart delete mode 100755 utils/template/template delete mode 100644 utils/template/template.dart delete mode 100644 utils/template/template.html delete mode 100644 utils/template/template_tool.html delete mode 100644 utils/template/temploptions.dart delete mode 100644 utils/template/token.dart delete mode 100644 utils/template/tokenizer.dart delete mode 100644 utils/template/tokenizer_base.dart delete mode 100644 utils/template/tokenkind.dart delete mode 100644 utils/template/tool.dart delete mode 100644 utils/template/tree.dart delete mode 100644 utils/template/uitest.dart delete mode 100644 utils/template/utils.dart delete mode 100644 utils/template/world.dart delete mode 100644 utils/tests/css/css.status delete mode 100644 utils/tests/css/declaration_test.dart delete mode 100644 utils/tests/css/expression_test.dart delete mode 100644 utils/tests/css/selector_literal_test.dart delete mode 100644 utils/tests/template/README.txt delete mode 100644 utils/tests/template/applications.tmpl delete mode 100644 utils/tests/template/applications2.tmpl delete mode 100644 utils/tests/template/callview.tmpl delete mode 100644 utils/tests/template/complex_datamodel.dart delete mode 100644 utils/tests/template/name_entry.tmpl delete mode 100644 utils/tests/template/name_entry2.tmpl delete mode 100644 utils/tests/template/name_entry_css.tmpl delete mode 100644 utils/tests/template/name_entry_simple.tmpl delete mode 100644 utils/tests/template/name_entry_text.tmpl delete mode 100644 utils/tests/template/nestedview.tmpl delete mode 100644 utils/tests/template/productview.tmpl delete mode 100644 utils/tests/template/productview2.tmpl delete mode 100644 utils/tests/template/productview3.tmpl delete mode 100644 utils/tests/template/productview_localname.tmpl delete mode 100644 utils/tests/template/real_app.dart delete mode 100644 utils/tests/template/realviews.tmpl delete mode 100755 utils/tests/template/run delete mode 100755 utils/tests/template/sample.dart delete mode 100644 utils/tests/template/test_complex.dart delete mode 100644 utils/tests/template/test_complex2.dart delete mode 100644 utils/tests/template/test_list.dart delete mode 100644 utils/tests/template/test_nested.dart delete mode 100755 utils/tests/template/test_simple.dart delete mode 100644 utils/tests/template/test_with.dart delete mode 100644 utils/tests/template/top_searches.tmpl delete mode 100644 utils/tests/template/top_searches2.tmpl delete mode 100644 utils/tests/template/top_searches_css.tmpl diff --git a/utils/css/css b/utils/css/css deleted file mode 100755 index 1dcc22d28b5b..000000000000 --- a/utils/css/css +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash - -# To pre-process CSS files, run this script with the path to a .scss file, like: -# -# $ $DART/utils/css/css foo.scss foo.css -# -# To use your Dart VM must be on your $PATH e.g., -# -# export PATH=$PATH:/home//dart-all/dart/out/Release_ia32/ - - -SRCFILE=$PWD/$1 -OUTPUT=$PWD/$2 -if [[ $1 == $2 ]] -then - echo -e "\033[31msource file must be different then output file\033[0m" - exit 1 -fi - -# Path of this bash script. -BASE_DIR="$( cd "$( dirname "$0" )" && pwd )" - -# Pre-process the file -dart $BASE_DIR/tool.dart $SRCFILE $OUTPUT - diff --git a/utils/css/css.dart b/utils/css/css.dart deleted file mode 100644 index e3c74f6b8750..000000000000 --- a/utils/css/css.dart +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library css; - -import 'dart:math' as Math; -import '../lib/file_system.dart'; -import '../lib/file_system_memory.dart'; - -part 'cssoptions.dart'; -part 'source.dart'; -part 'tokenkind.dart'; -part 'token.dart'; -part 'tokenizer_base.dart'; -part 'tokenizer.dart'; -part 'treebase.dart'; -part 'tree.dart'; -part 'cssselectorexception.dart'; -part 'cssworld.dart'; -part 'parser.dart'; -part 'validate.dart'; -part 'generate.dart'; -part 'world.dart'; - - -void initCssWorld([bool commandLine = true]) { - FileSystem fs = new MemoryFileSystem(); - parseOptions([], fs); - initializeWorld(fs); - - // TODO(terry): Should be set by arguments. When run as a tool these aren't - // set when run internaly set these so we can compile CSS and catch any - // problems programmatically. - options.throwOnErrors = true; - options.throwOnFatal = true; - options.useColors = commandLine ? true : false; - options.warningsAsErrors = false; - options.showWarnings = true; -} - -// TODO(terry): Add obfuscation mapping file. -void cssParseAndValidate(String cssExpression, CssWorld cssworld) { - Parser parser = new Parser(new SourceFile(SourceFile.IN_MEMORY_FILE, - cssExpression)); - var tree = parser.parseTemplate(); - if (tree != null) { - Validate.template(tree.selectors, cssworld); - } -} - -// Returns pretty printed tree of the expression. -String cssParseAndValidateDebug(String cssExpression, CssWorld cssworld) { - Parser parser = new Parser(new SourceFile(SourceFile.IN_MEMORY_FILE, - cssExpression)); - String output = ""; - String prettyTree = ""; - try { - var tree = parser.parseTemplate(); - if (tree != null) { - prettyTree = tree.toDebugString(); - Validate.template(tree.selectors, cssworld); - output = prettyTree; - } - } catch (e) { - String error = e.toString(); - output = "$error\n$prettyTree"; - throw e; - } - - return output; -} diff --git a/utils/css/css.html b/utils/css/css.html deleted file mode 100755 index bf1ec18eafc6..000000000000 --- a/utils/css/css.html +++ /dev/null @@ -1,8 +0,0 @@ - - - CSS UITest - - - - - diff --git a/utils/css/cssoptions.dart b/utils/css/cssoptions.dart deleted file mode 100644 index 8193d65c721b..000000000000 --- a/utils/css/cssoptions.dart +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -/** General options used by the compiler. */ -CSSOptions options; - -/** Extracts options from command-line arguments. */ -void parseOptions(List args, var files) { - assert(options == null); - options = new CSSOptions(args, files); -} - -class CSSOptions { - /** Location of corelib and other special dart libraries. */ - String libDir; - - /* The top-level dart script to compile. */ - String dartScript; - - /** Where to place the generated code. */ - String outfile; - - // Options that modify behavior significantly - - bool warningsAsErrors = false; - bool checkOnly = false; - - // Message support - bool throwOnErrors = false; - bool throwOnWarnings = false; - bool throwOnFatal = false; - bool showInfo = false; - bool showWarnings = true; - bool useColors = true; - - /** - * Options to be used later for passing to the generated code. These are all - * the arguments after the first dart script, if any. - */ - List childArgs; - - CSSOptions(List args, var files) { - bool ignoreUnrecognizedFlags = false; - bool passedLibDir = false; - childArgs = []; - - // Start from 2 to skip arguments representing the compiler command - // (python followed by frog.py). - for (int i = 2; i < args.length; i++) { - var arg = args[i]; - - switch (arg) { - case '--check-only': - checkOnly = true; - break; - - case '--verbose': - showInfo = true; - break; - - case '--suppress_warnings': - showWarnings = false; - break; - - case '--warnings_as_errors': - warningsAsErrors = true; - break; - - case '--throw_on_errors': - throwOnErrors = true; - break; - - case '--throw_on_warnings': - throwOnWarnings = true; - break; - - case '--no_colors': - useColors = false; - break; - - case '--checked': - checkOnly = true; - break; - - default: - if (!ignoreUnrecognizedFlags) { - print('unrecognized flag: "$arg"'); - } - } - } - } -} diff --git a/utils/css/cssselectorexception.dart b/utils/css/cssselectorexception.dart deleted file mode 100644 index 2077ed798618..000000000000 --- a/utils/css/cssselectorexception.dart +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -// TODO(terry): Rename CompilerException to be SourceException then this -// exception would be derived from SourceException. - -/** Can be thrown on any Css runtime problem includes source location. */ -class CssSelectorException implements Exception { - final String _message; - final SourceSpan _location; - - CssSelectorException(this._message, [this._location = null]); - - String toString() { - if (_location != null) { - return 'CssSelectorException: ${_location.toMessageString(_message)}'; - } else { - return 'CssSelectorException: $_message'; - } - } - -} diff --git a/utils/css/cssworld.dart b/utils/css/cssworld.dart deleted file mode 100644 index 281b2b7b0a54..000000000000 --- a/utils/css/cssworld.dart +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -class CssWorld { - List classes; - List ids; - - CssWorld(this.classes, this.ids) { - // Insure no private class names in our CSS world (._foo). - for (final aClass in classes) { - if (aClass.startsWith('_')) { - throw new CssSelectorException( - "private class ('_' prefix) not valid for CssWorld $aClass)"); - } - } - - // Insure no private element ids in our CSS world (#_foo). - for (final id in ids) { - if (id.startsWith('_')) { - throw new CssSelectorException( - "private id ('_' prefix) not valid for CssWorld $id)"); - } - } - } -} diff --git a/utils/css/generate.dart b/utils/css/generate.dart deleted file mode 100644 index 2d248451ac2c..000000000000 --- a/utils/css/generate.dart +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -class Generate { - - // Build up list of all known class selectors in all CSS files. - static List computeClassSelectors(RuleSet ruleset, classes) { - for (final selector in ruleset.selectorGroup.selectors) { - var selSeqs = selector.simpleSelectorSequences; - for (final selSeq in selSeqs) { - var simpleSelector = selSeq.simpleSelector; - if (simpleSelector is ClassSelector) { - String className = simpleSelector.name; - if (classes.indexOf(className) == -1) { // Class name already known? - // No, expose it. - classes.add(className); - } - } - } - } - - return classes; - } - - static dartClass(var files, String outPath, Stylesheet stylesheet, - String filename) { - - List knownClasses = []; - - StringBuffer buff = new StringBuffer( - '// File generated by Dart CSS from source file ${filename}\n' + - '// Do not edit.\n\n'); - - // Emit class for any @stylet directive. - for (final production in stylesheet._topLevels) { - if (production is Directive) { - if (production is StyletDirective) { - // TODO(terry): Need safer mechanism for stylets in different files - // and stylets with colliding names. - buff.write('class ${production.dartClassName} {\n'); - buff.write(' // selector, properties\n'); - buff.write(' static const selectors = const {\n'); - - for (final ruleset in production.rulesets) { - for (final selector in ruleset.selectorGroup.selectors) { - var selSeq = selector.simpleSelectorSquences; - if (selSeq.length == 1) { - buff.write(' \'${selSeq.toString()}\' : const {\n'); - } - } - - for (final decl in ruleset.declarationGroup.declarations) { - buff.write(' \'${decl.property}\' : ' + - '\'${decl.expression.toString()}\',\n'); - } - buff.write(' },\n'); // End of declarations for stylet class. - } - buff.write(' };\n'); // End of static selectors constant. - buff.write('}\n\n'); // End of stylet class - } else if (production is IncludeDirective) { - for (final topLevel in production.styleSheet._topLevels) { - if (topLevel is RuleSet) { - knownClasses = computeClassSelectors(topLevel, knownClasses); - } - } - } - } else if (production is RuleSet) { - knownClasses = computeClassSelectors(production, knownClasses); - } - } - - // Generate all known classes encountered in all processed CSS files. - StringBuffer classSelectors = new StringBuffer( - 'class CSS {\n' + - ' // CSS class selectors:\n'); - for (final className in knownClasses) { - String classAsDart = className.replaceAll('-', '_').toUpperCase(); - classSelectors.write(' static const String ${classAsDart} = ' + - '\'${className}\';\n'); - } - classSelectors.write('}\n'); // End of class selectors. - buff.write(classSelectors.toString()); - - // Write Dart file. - String outFile = '${outPath}CSS.dart'; - files.writeString(outFile, buff.toString()); - - return outFile; - } -} - diff --git a/utils/css/parser.dart b/utils/css/parser.dart deleted file mode 100644 index a865bdf2760b..000000000000 --- a/utils/css/parser.dart +++ /dev/null @@ -1,1017 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a - -/** - * A simple recursive descent parser for CSS. - */ -class Parser { - Tokenizer tokenizer; - - var _fs; // If non-null filesystem to read files. - String _basePath; // Base path of CSS file. - - final SourceFile source; - - Token _previousToken; - Token _peekToken; - -// Communicating errors back to template parser. -// TODO(terry): Need a better mechanism (e.g., common World). - var _erroMsgRedirector; - - Parser(this.source, [int start = 0, this._fs = null, this._basePath = null]) { - tokenizer = new Tokenizer(source, true, start); - _peekToken = tokenizer.next(); - _previousToken = null; - } - - // Main entry point for parsing an entire CSS file. - // If nestedCSS is true when we're back at processing directives from top and - // we encounter a } then stop we're inside of a template e.g., - // - // template ... { - // css { - // .item { - // left: 10px; - // } - // } - //
...
- // } - // - Stylesheet parse([bool nestedCSS = false, var erroMsgRedirector = null]) { - // TODO(terry): Hack for migrating CSS errors back to template errors. - _erroMsgRedirector = erroMsgRedirector; - - List productions = []; - - int start = _peekToken.start; - while (!_maybeEat(TokenKind.END_OF_FILE) && - (!nestedCSS && !_peekKind(TokenKind.RBRACE))) { - // TODO(terry): Need to handle charset, import, media and page. - var directive = processDirective(); - if (directive != null) { - productions.add(directive); - } else { - RuleSet ruleset = processRuleSet(); - if (ruleset != null) { - productions.add(ruleset); - } else { - break; - } - } - } - - return new Stylesheet(productions, _makeSpan(start)); - } - - /** Generate an error if [source] has not been completely consumed. */ - void checkEndOfFile() { - _eat(TokenKind.END_OF_FILE); - } - - /** Guard to break out of parser when an unexpected end of file is found. */ - // TODO(jimhug): Failure to call this method can lead to inifinite parser - // loops. Consider embracing exceptions for more errors to reduce - // the danger here. - bool isPrematureEndOfFile() { - if (_maybeEat(TokenKind.END_OF_FILE)) { - _error('unexpected end of file', _peekToken.span); - return true; - } else { - return false; - } - } - - /////////////////////////////////////////////////////////////////// - // Basic support methods - /////////////////////////////////////////////////////////////////// - int _peek() { - return _peekToken.kind; - } - - Token _next() { - _previousToken = _peekToken; - _peekToken = tokenizer.next(); - return _previousToken; - } - - bool _peekKind(int kind) { - return _peekToken.kind == kind; - } - - /* Is the next token a legal identifier? This includes pseudo-keywords. */ - bool _peekIdentifier() { - return TokenKind.isIdentifier(_peekToken.kind); - } - - bool _maybeEat(int kind) { - if (_peekToken.kind == kind) { - _previousToken = _peekToken; - _peekToken = tokenizer.next(); - return true; - } else { - return false; - } - } - - void _eat(int kind) { - if (!_maybeEat(kind)) { - _errorExpected(TokenKind.kindToString(kind)); - } - } - - void _eatSemicolon() { - _eat(TokenKind.SEMICOLON); - } - - void _errorExpected(String expected) { - var tok = _next(); - var message; - try { - message = 'expected $expected, but found $tok'; - } catch (e) { - message = 'parsing error expected $expected'; - } - _error(message, tok.span); - } - - void _error(String message, [SourceSpan location=null]) { - if (location == null) { - location = _peekToken.span; - } - - if (_erroMsgRedirector == null) { - world.fatal(message, location); // syntax errors are fatal for now - } else { - String text = ""; - if (location != null) { - text = location.toMessageString(""); - } - _erroMsgRedirector.displayError("CSS error: \r${text}\r${message}"); - } - } - - void _warning(String message, [SourceSpan location=null]) { - if (location == null) { - location = _peekToken.span; - } - - world.warning(message, location); - } - - SourceSpan _makeSpan(int start) { - return new SourceSpan(source, start, _previousToken.end); - } - - /////////////////////////////////////////////////////////////////// - // Top level productions - /////////////////////////////////////////////////////////////////// - - // Templates are @{selectors} single line nothing else. - SelectorGroup parseTemplate() { - SelectorGroup selectorGroup = null; - if (!isPrematureEndOfFile()) { - selectorGroup = templateExpression(); - } - - return selectorGroup; - } - - /* - * Expect @{css_expression} - */ - templateExpression() { - List selectors = []; - - int start = _peekToken.start; - - _eat(TokenKind.AT); - _eat(TokenKind.LBRACE); - - selectors.add(processSelector()); - SelectorGroup group = new SelectorGroup(selectors, _makeSpan(start)); - - _eat(TokenKind.RBRACE); - - return group; - } - - /////////////////////////////////////////////////////////////////// - // Productions - /////////////////////////////////////////////////////////////////// - - processMedia([bool oneRequired = false]) { - List media = []; - - while (_peekIdentifier()) { - // We have some media types. - var medium = identifier(); // Medium ident. - media.add(medium); - if (!_maybeEat(TokenKind.COMMA)) { - // No more media types exit now. - break; - } - } - - if (oneRequired && media.length == 0) { - _error('at least one media type required', _peekToken.span); - } - - return media; - } - - // Directive grammar: - // - // import: '@import' [string | URI] media_list? - // media: '@media' media_list '{' ruleset '}' - // page: '@page' [':' IDENT]? '{' declarations '}' - // include: '@include' [string | URI] - // stylet: '@stylet' IDENT '{' ruleset '}' - // media_list: IDENT [',' IDENT] - // keyframes: '@-webkit-keyframes ...' (see grammar below). - // font_face: '@font-face' '{' declarations '}' - // - processDirective() { - int start = _peekToken.start; - - if (_maybeEat(TokenKind.AT)) { - switch (_peek()) { - case TokenKind.DIRECTIVE_IMPORT: - _next(); - - String importStr; - if (_peekIdentifier()) { - var func = processFunction(identifier()); - if (func is UriTerm) { - importStr = func.text; - } - } else { - importStr = processQuotedString(false); - } - - // Any medias? - List medias = processMedia(); - - if (importStr == null) { - _error('missing import string', _peekToken.span); - } - return new ImportDirective(importStr, medias, _makeSpan(start)); - case TokenKind.DIRECTIVE_MEDIA: - _next(); - - // Any medias? - List media = processMedia(true); - RuleSet ruleset; - - if (_maybeEat(TokenKind.LBRACE)) { - ruleset = processRuleSet(); - if (!_maybeEat(TokenKind.RBRACE)) { - _error('expected } after ruleset for @media', _peekToken.span); - } - } else { - _error('expected { after media before ruleset', _peekToken.span); - } - return new MediaDirective(media, ruleset, _makeSpan(start)); - case TokenKind.DIRECTIVE_PAGE: - _next(); - - // Any pseudo page? - var pseudoPage; - if (_maybeEat(TokenKind.COLON)) { - if (_peekIdentifier()) { - pseudoPage = identifier(); - } - } - return new PageDirective(pseudoPage, processDeclarations(), - _makeSpan(start)); - case TokenKind.DIRECTIVE_KEYFRAMES: - /* Key frames grammar: - * - * @-webkit-keyframes [IDENT|STRING] '{' keyframes-blocks '}'; - * - * keyframes-blocks: - * [keyframe-selectors '{' declarations '}']* ; - * - * keyframe-selectors: - * ['from'|'to'|PERCENTAGE] [',' ['from'|'to'|PERCENTAGE] ]* ; - */ - _next(); - - var name; - if (_peekIdentifier()) { - name = identifier(); - } - - _eat(TokenKind.LBRACE); - - KeyFrameDirective kf = new KeyFrameDirective(name, _makeSpan(start)); - - do { - Expressions selectors = new Expressions(_makeSpan(start)); - - do { - var term = processTerm(); - - // TODO(terry): Only allow from, to and PERCENTAGE ... - - selectors.add(term); - } while (_maybeEat(TokenKind.COMMA)); - - kf.add(new KeyFrameBlock(selectors, processDeclarations(), - _makeSpan(start))); - - } while (!_maybeEat(TokenKind.RBRACE)); - - return kf; - case TokenKind.DIRECTIVE_FONTFACE: - _next(); - - List decls = []; - - // TODO(terry): To Be Implemented - - return new FontFaceDirective(decls, _makeSpan(start)); - case TokenKind.DIRECTIVE_INCLUDE: - _next(); - String filename = processQuotedString(false); - if (_fs != null) { - // Does CSS file exist? - if (_fs.fileExists('${_basePath}${filename}')) { - String basePath = ""; - int idx = filename.lastIndexOf('/'); - if (idx >= 0) { - basePath = filename.substring(0, idx + 1); - } - basePath = '${_basePath}${basePath}'; - // Yes, let's parse this file as well. - String fullFN = '${basePath}${filename}'; - String contents = _fs.readAll(fullFN); - Parser parser = new Parser(new SourceFile(fullFN, contents), 0, - _fs, basePath); - Stylesheet stylesheet = parser.parse(); - return new IncludeDirective(filename, stylesheet, _makeSpan(start)); - } - - _error('file doesn\'t exist ${filename}', _peekToken.span); - } - - print("WARNING: @include doesn't work for uitest"); - return new IncludeDirective(filename, null, _makeSpan(start)); - case TokenKind.DIRECTIVE_STYLET: - /* Stylet grammar: - * - * @stylet IDENT '{' - * ruleset - * '}' - */ - _next(); - - var name; - if (_peekIdentifier()) { - name = identifier(); - } - - _eat(TokenKind.LBRACE); - - List productions = []; - - start = _peekToken.start; - while (!_maybeEat(TokenKind.END_OF_FILE)) { - RuleSet ruleset = processRuleSet(); - if (ruleset == null) { - break; - } - productions.add(ruleset); - } - - _eat(TokenKind.RBRACE); - - return new StyletDirective(name, productions, _makeSpan(start)); - default: - _error('unknown directive, found $_peekToken', _peekToken.span); - } - } - } - - RuleSet processRuleSet() { - int start = _peekToken.start; - - SelectorGroup selGroup = processSelectorGroup(); - if (selGroup != null) { - return new RuleSet(selGroup, processDeclarations(), _makeSpan(start)); - } - } - - DeclarationGroup processDeclarations() { - int start = _peekToken.start; - - _eat(TokenKind.LBRACE); - - List decls = []; - do { - Declaration decl = processDeclaration(); - if (decl != null) { - decls.add(decl); - } - } while (_maybeEat(TokenKind.SEMICOLON)); - - _eat(TokenKind.RBRACE); - - return new DeclarationGroup(decls, _makeSpan(start)); - } - - SelectorGroup processSelectorGroup() { - List selectors = []; - int start = _peekToken.start; - do { - Selector selector = processSelector(); - if (selector != null) { - selectors.add(selector); - } - } while (_maybeEat(TokenKind.COMMA)); - - if (selectors.length > 0) { - return new SelectorGroup(selectors, _makeSpan(start)); - } - } - - /* Return list of selectors - * - */ - processSelector() { - List simpleSequences = []; - int start = _peekToken.start; - while (true) { - // First item is never descendant make sure it's COMBINATOR_NONE. - var selectorItem = simpleSelectorSequence(simpleSequences.length == 0); - if (selectorItem != null) { - simpleSequences.add(selectorItem); - } else { - break; - } - } - - if (simpleSequences.length > 0) { - return new Selector(simpleSequences, _makeSpan(start)); - } - } - - simpleSelectorSequence(bool forceCombinatorNone) { - int start = _peekToken.start; - int combinatorType = TokenKind.COMBINATOR_NONE; - - switch (_peek()) { - case TokenKind.PLUS: - _eat(TokenKind.PLUS); - combinatorType = TokenKind.COMBINATOR_PLUS; - break; - case TokenKind.GREATER: - _eat(TokenKind.GREATER); - combinatorType = TokenKind.COMBINATOR_GREATER; - break; - case TokenKind.TILDE: - _eat(TokenKind.TILDE); - combinatorType = TokenKind.COMBINATOR_TILDE; - break; - } - - // Check if WHITESPACE existed between tokens if so we're descendent. - if (combinatorType == TokenKind.COMBINATOR_NONE && !forceCombinatorNone) { - if (this._previousToken != null && - this._previousToken.end != this._peekToken.start) { - combinatorType = TokenKind.COMBINATOR_DESCENDANT; - } - } - - var simpleSel = simpleSelector(); - if (simpleSel != null) { - return new SimpleSelectorSequence(simpleSel, _makeSpan(start), - combinatorType); - } - } - - /** - * Simple selector grammar: - * - * simple_selector_sequence - * : [ type_selector | universal ] - * [ HASH | class | attrib | pseudo | negation ]* - * | [ HASH | class | attrib | pseudo | negation ]+ - * type_selector - * : [ namespace_prefix ]? element_name - * namespace_prefix - * : [ IDENT | '*' ]? '|' - * element_name - * : IDENT - * universal - * : [ namespace_prefix ]? '*' - * class - * : '.' IDENT - */ - simpleSelector() { - // TODO(terry): Nathan makes a good point parsing of namespace and element - // are essentially the same (asterisk or identifier) other - // than the error message for element. Should consolidate the - // code. - // TODO(terry): Need to handle attribute namespace too. - var first; - int start = _peekToken.start; - switch (_peek()) { - case TokenKind.ASTERISK: - // Mark as universal namespace. - var tok = _next(); - first = new Wildcard(_makeSpan(tok.start)); - break; - case TokenKind.IDENTIFIER: - int startIdent = _peekToken.start; - first = identifier(); - break; - } - - if (_maybeEat(TokenKind.NAMESPACE)) { - var element; - switch (_peek()) { - case TokenKind.ASTERISK: - // Mark as universal element - var tok = _next(); - element = new Wildcard(_makeSpan(tok.start)); - break; - case TokenKind.IDENTIFIER: - element = identifier(); - break; - default: - _error('expected element name or universal(*), but found $_peekToken', - _peekToken.span); - } - - return new NamespaceSelector(first, - new ElementSelector(element, element.span), _makeSpan(start)); - } else if (first != null) { - return new ElementSelector(first, _makeSpan(start)); - } else { - // Check for HASH | class | attrib | pseudo | negation - return simpleSelectorTail(); - } - } - - simpleSelectorTail() { - // Check for HASH | class | attrib | pseudo | negation - int start = _peekToken.start; - switch (_peek()) { - case TokenKind.HASH: - _eat(TokenKind.HASH); - return new IdSelector(identifier(), _makeSpan(start)); - case TokenKind.DOT: - _eat(TokenKind.DOT); - return new ClassSelector(identifier(), _makeSpan(start)); - case TokenKind.COLON: - // :pseudo-class ::pseudo-element - // TODO(terry): '::' should be token. - _eat(TokenKind.COLON); - bool pseudoElement = _maybeEat(TokenKind.COLON); - var name = identifier(); - // TODO(terry): Need to handle specific pseudo class/element name and - // backward compatible names that are : as well as :: as well as - // parameters. - return pseudoElement ? - new PseudoElementSelector(name, _makeSpan(start)) : - new PseudoClassSelector(name, _makeSpan(start)); - case TokenKind.LBRACK: - return processAttribute(); - } - } - - // Attribute grammar: - // - // attributes : - // '[' S* IDENT S* [ ATTRIB_MATCHES S* [ IDENT | STRING ] S* ]? ']' - // - // ATTRIB_MATCHES : - // [ '=' | INCLUDES | DASHMATCH | PREFIXMATCH | SUFFIXMATCH | SUBSTRMATCH ] - // - // INCLUDES: '~=' - // - // DASHMATCH: '|=' - // - // PREFIXMATCH: '^=' - // - // SUFFIXMATCH: '$=' - // - // SUBSTRMATCH: '*=' - // - // - processAttribute() { - int start = _peekToken.start; - - if (_maybeEat(TokenKind.LBRACK)) { - var attrName = identifier(); - - int op = TokenKind.NO_MATCH; - switch (_peek()) { - case TokenKind.EQUALS: - case TokenKind.INCLUDES: // ~= - case TokenKind.DASH_MATCH: // |= - case TokenKind.PREFIX_MATCH: // ^= - case TokenKind.SUFFIX_MATCH: // $= - case TokenKind.SUBSTRING_MATCH: // *= - op = _peek(); - _next(); - break; - } - - String value; - if (op != TokenKind.NO_MATCH) { - // Operator hit so we require a value too. - if (_peekIdentifier()) { - value = identifier(); - } else { - value = processQuotedString(false); - } - - if (value == null) { - _error('expected attribute value string or ident', _peekToken.span); - } - } - - _eat(TokenKind.RBRACK); - - return new AttributeSelector(attrName, op, value, _makeSpan(start)); - } - } - - // Declaration grammar: - // - // declaration: property ':' expr prio? - // - // property: IDENT - // prio: !important - // expr: (see processExpr) - // - processDeclaration() { - Declaration decl; - - int start = _peekToken.start; - - // IDENT ':' expr '!important'? - if (TokenKind.isIdentifier(_peekToken.kind)) { - var propertyIdent = identifier(); - _eat(TokenKind.COLON); - - decl = new Declaration(propertyIdent, processExpr(), _makeSpan(start)); - - // Handle !important (prio) - decl.important = _maybeEat(TokenKind.IMPORTANT); - } - - return decl; - } - - // Expression grammar: - // - // expression: term [ operator? term]* - // - // operator: '/' | ',' - // term: (see processTerm) - // - processExpr() { - int start = _peekToken.start; - Expressions expressions = new Expressions(_makeSpan(start)); - - bool keepGoing = true; - var expr; - while (keepGoing && (expr = processTerm()) != null) { - var op; - - int opStart = _peekToken.start; - - switch (_peek()) { - case TokenKind.SLASH: - op = new OperatorSlash(_makeSpan(opStart)); - break; - case TokenKind.COMMA: - op = new OperatorComma(_makeSpan(opStart)); - break; - } - - if (expr != null) { - expressions.add(expr); - } else { - keepGoing = false; - } - - if (op != null) { - expressions.add(op); - _next(); - } - } - - return expressions; - } - - // Term grammar: - // - // term: - // unary_operator? - // [ term_value ] - // | STRING S* | IDENT S* | URI S* | UNICODERANGE S* | hexcolor - // - // term_value: - // NUMBER S* | PERCENTAGE S* | LENGTH S* | EMS S* | EXS S* | ANGLE S* | - // TIME S* | FREQ S* | function - // - // NUMBER: {num} - // PERCENTAGE: {num}% - // LENGTH: {num}['px' | 'cm' | 'mm' | 'in' | 'pt' | 'pc'] - // EMS: {num}'em' - // EXS: {num}'ex' - // ANGLE: {num}['deg' | 'rad' | 'grad'] - // TIME: {num}['ms' | 's'] - // FREQ: {num}['hz' | 'khz'] - // function: IDENT '(' expr ')' - // - processTerm() { - int start = _peekToken.start; - Token t; // token for term's value - var value; // value of term (numeric values) - - var unary = ""; - - switch (_peek()) { - case TokenKind.HASH: - this._eat(TokenKind.HASH); - String hexText; - if (_peekKind(TokenKind.INTEGER)) { - String hexText1 = _peekToken.text; - _next(); - if (_peekIdentifier()) { - hexText = '${hexText1}${identifier().name}'; - } else { - hexText = hexText1; - } - } else if (_peekIdentifier()) { - hexText = identifier().name; - } else { - _errorExpected("hex number"); - } - - try { - int hexValue = parseHex(hexText); - return new HexColorTerm(hexValue, hexText, _makeSpan(start)); - } on HexNumberException catch (hne) { - _error('Bad hex number', _makeSpan(start)); - } - break; - case TokenKind.INTEGER: - t = _next(); - value = int.parse("${unary}${t.text}"); - break; - case TokenKind.DOUBLE: - t = _next(); - value = double.parse("${unary}${t.text}"); - break; - case TokenKind.SINGLE_QUOTE: - case TokenKind.DOUBLE_QUOTE: - value = processQuotedString(false); - value = '"${value}"'; - return new LiteralTerm(value, value, _makeSpan(start)); - case TokenKind.LPAREN: - _next(); - - GroupTerm group = new GroupTerm(_makeSpan(start)); - - do { - var term = processTerm(); - if (term != null && term is LiteralTerm) { - group.add(term); - } - } while (!_maybeEat(TokenKind.RPAREN)); - - return group; - case TokenKind.LBRACK: - _next(); - - var term = processTerm(); - if (!(term is NumberTerm)) { - _error('Expecting a positive number', _makeSpan(start)); - } - - _eat(TokenKind.RBRACK); - - return new ItemTerm(term.value, term.text, _makeSpan(start)); - case TokenKind.IDENTIFIER: - var nameValue = identifier(); // Snarf up the ident we'll remap, maybe. - - if (_maybeEat(TokenKind.LPAREN)) { - // FUNCTION - return processFunction(nameValue); - } else { - // TODO(terry): Need to have a list of known identifiers today only - // 'from' is special. - if (nameValue.name == 'from') { - return new LiteralTerm(nameValue, nameValue.name, _makeSpan(start)); - } - - // What kind of identifier is it? - try { - // Named color? - int colorValue = TokenKind.matchColorName(nameValue.name); - - // Yes, process the color as an RGB value. - String rgbColor = TokenKind.decimalToHex(colorValue, 3); - try { - colorValue = parseHex(rgbColor); - } on HexNumberException catch (hne) { - _error('Bad hex number', _makeSpan(start)); - } - return new HexColorTerm(colorValue, rgbColor, _makeSpan(start)); - } catch (error) { - if (error is NoColorMatchException) { - // TODO(terry): Other named things to match with validator? - - // TODO(terry): Disable call to _warning need one World class for - // both CSS parser and other parser (e.g., template) - // so all warnings, errors, options, etc. are driven - // from the one World. -// _warning('Unknown property value ${error.name}', _makeSpan(start)); - return new LiteralTerm(nameValue, nameValue.name, _makeSpan(start)); - } - } - } - } - - var term; - var unitType = this._peek(); - - switch (unitType) { - case TokenKind.UNIT_EM: - term = new EmTerm(value, t.text, _makeSpan(start)); - _next(); // Skip the unit - break; - case TokenKind.UNIT_EX: - term = new ExTerm(value, t.text, _makeSpan(start)); - _next(); // Skip the unit - break; - case TokenKind.UNIT_LENGTH_PX: - case TokenKind.UNIT_LENGTH_CM: - case TokenKind.UNIT_LENGTH_MM: - case TokenKind.UNIT_LENGTH_IN: - case TokenKind.UNIT_LENGTH_PT: - case TokenKind.UNIT_LENGTH_PC: - term = new LengthTerm(value, t.text, _makeSpan(start), unitType); - _next(); // Skip the unit - break; - case TokenKind.UNIT_ANGLE_DEG: - case TokenKind.UNIT_ANGLE_RAD: - case TokenKind.UNIT_ANGLE_GRAD: - term = new AngleTerm(value, t.text, _makeSpan(start), unitType); - _next(); // Skip the unit - break; - case TokenKind.UNIT_TIME_MS: - case TokenKind.UNIT_TIME_S: - term = new TimeTerm(value, t.text, _makeSpan(start), unitType); - _next(); // Skip the unit - break; - case TokenKind.UNIT_FREQ_HZ: - case TokenKind.UNIT_FREQ_KHZ: - term = new FreqTerm(value, t.text, _makeSpan(start), unitType); - _next(); // Skip the unit - break; - case TokenKind.PERCENT: - term = new PercentageTerm(value, t.text, _makeSpan(start)); - _next(); // Skip the % - break; - case TokenKind.UNIT_FRACTION: - term = new FractionTerm(value, t.text, _makeSpan(start)); - _next(); // Skip the unit - break; - default: - if (value != null) { - term = new NumberTerm(value, t.text, _makeSpan(start)); - } - } - - return term; - } - - processQuotedString([bool urlString = false]) { - int start = _peekToken.start; - - // URI term sucks up everything inside of quotes(' or ") or between parens - int stopToken = urlString ? TokenKind.RPAREN : -1; - switch (_peek()) { - case TokenKind.SINGLE_QUOTE: - stopToken = TokenKind.SINGLE_QUOTE; - _next(); // Skip the SINGLE_QUOTE. - break; - case TokenKind.DOUBLE_QUOTE: - stopToken = TokenKind.DOUBLE_QUOTE; - _next(); // Skip the DOUBLE_QUOTE. - break; - default: - if (urlString) { - if (_peek() == TokenKind.LPAREN) { - _next(); // Skip the LPAREN. - } - stopToken = TokenKind.RPAREN; - } else { - _error('unexpected string', _makeSpan(start)); - } - } - - StringBuffer stringValue = new StringBuffer(); - - // Gobble up everything until we hit our stop token. - int runningStart = _peekToken.start; - while (_peek() != stopToken && _peek() != TokenKind.END_OF_FILE) { - var tok = _next(); - stringValue.write(tok.text); - } - - if (stopToken != TokenKind.RPAREN) { - _next(); // Skip the SINGLE_QUOTE or DOUBLE_QUOTE; - } - - return stringValue.toString(); - } - - // Function grammar: - // - // function: IDENT '(' expr ')' - // - processFunction(Identifier func) { - int start = _peekToken.start; - - String name = func.name; - - switch (name) { - case 'url': - // URI term sucks up everything inside of quotes(' or ") or between parens - String urlParam = processQuotedString(true); - - // TODO(terry): Better error messge and checking for mismatched quotes. - if (_peek() == TokenKind.END_OF_FILE) { - _error("problem parsing URI", _peekToken.span); - } - - if (_peek() == TokenKind.RPAREN) { - _next(); - } - - return new UriTerm(urlParam, _makeSpan(start)); - case 'calc': - // TODO(terry): Implement expression handling... - break; - default: - var expr = processExpr(); - if (!_maybeEat(TokenKind.RPAREN)) { - _error("problem parsing function expected ), ", _peekToken.span); - } - - return new FunctionTerm(name, name, expr, _makeSpan(start)); - } - - return null; - } - - identifier() { - var tok = _next(); - if (!TokenKind.isIdentifier(tok.kind)) { - _error('expected identifier, but found $tok', tok.span); - } - - return new Identifier(tok.text, _makeSpan(tok.start)); - } - - // TODO(terry): Move this to base <= 36 and into shared code. - static int _hexDigit(int c) { - if(c >= 48/*0*/ && c <= 57/*9*/) { - return c - 48; - } else if (c >= 97/*a*/ && c <= 102/*f*/) { - return c - 87; - } else if (c >= 65/*A*/ && c <= 70/*F*/) { - return c - 55; - } else { - return -1; - } - } - - static int parseHex(String hex) { - var result = 0; - - for (int i = 0; i < hex.length; i++) { - var digit = _hexDigit(hex.codeUnitAt(i)); - if (digit < 0) { - throw new HexNumberException(); - } - result = (result << 4) + digit; - } - - return result; - } -} - -/** Not a hex number. */ -class HexNumberException implements Exception { - HexNumberException(); -} - diff --git a/utils/css/source.dart b/utils/css/source.dart deleted file mode 100644 index 5eeb0e2a3c9d..000000000000 --- a/utils/css/source.dart +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -// TODO(jimhug): This should be an interface to work better with tools. -/** - * Represents a file of source code. - */ -class SourceFile implements Comparable { - // TODO(terry): This filename for in memory buffer. May need to rework if - // filename is used for more than informational. - static String IN_MEMORY_FILE = ''; - - /** The name of the file. */ - final String filename; - - /** The text content of the file. */ - String _text; - - /** - * The order of the source file in a given library. This is used while we're - * writing code for a library. A single source file can be used - */ - // TODO(jmesserly): I don't like having properties that are only valid - // sometimes. An alternative would be to store it in a Map that's used by - // WorldGenerator while it's emitting code. This seems simpler. - int orderInLibrary; - - List _lineStarts; - - SourceFile(this.filename, this._text); - - String get text => _text; - - set text(String newText) { - if (newText != _text) { - _text = newText; - _lineStarts = null; - orderInLibrary = null; - } - } - - List get lineStarts { - if (_lineStarts == null) { - var starts = [0]; - var index = 0; - while (index < text.length) { - index = text.indexOf('\n', index) + 1; - if (index <= 0) break; - starts.add(index); - } - starts.add(text.length + 1); - _lineStarts = starts; - } - return _lineStarts; - } - - int getLine(int position) { - // TODO(jimhug): Implement as binary search. - var starts = lineStarts; - for (int i=0; i < starts.length; i++) { - if (starts[i] > position) return i-1; - } - world.internalError('bad position'); - } - - int getColumn(int line, int position) { - return position - lineStarts[line]; - } - - /** - * Create a pretty string representation from a character position - * in the file. - */ - String getLocationMessage(String message, int start, - [int end, bool includeText=false]) { - var line = getLine(start); - var column = getColumn(line, start); - - var buf = new StringBuffer( - '${filename}:${line + 1}:${column + 1}: $message'); - if (includeText) { - buf.write('\n'); - var textLine; - // +1 for 0-indexing, +1 again to avoid the last line of the file - if ((line + 2) < _lineStarts.length) { - textLine = text.substring(_lineStarts[line], _lineStarts[line+1]); - } else { - textLine = text.substring(_lineStarts[line]) + '\n'; - } - - int toColumn = Math.min(column + (end-start), textLine.length); - if (options.useColors) { - buf.write(textLine.substring(0, column)); - buf.write(_RED_COLOR); - buf.write(textLine.substring(column, toColumn)); - buf.write(_NO_COLOR); - buf.write(textLine.substring(toColumn)); - } else { - buf.write(textLine); - } - - int i = 0; - for (; i < column; i++) { - buf.write(' '); - } - - if (options.useColors) buf.write(_RED_COLOR); - for (; i < toColumn; i++) { - buf.write('^'); - } - if (options.useColors) buf.write(_NO_COLOR); - } - - return buf.toString(); - } - - /** Compares two source files. */ - int compareTo(SourceFile other) { - if (orderInLibrary != null && other.orderInLibrary != null) { - return orderInLibrary - other.orderInLibrary; - } else { - return filename.compareTo(other.filename); - } - } -} - - -/** - * A range of characters in a [SourceFile]. Used to represent the source - * positions of [Token]s and [Node]s for error reporting or other tooling - * work. - */ - // TODO(jmesserly): Rename to Span - but first write cool refactoring tool -class SourceSpan implements Comparable { - /** The [SourceFile] that contains this span. */ - final SourceFile file; - - /** The character position of the start of this span. */ - final int start; - - /** The character position of the end of this span. */ - final int end; - - SourceSpan(this.file, this.start, this.end); - - /** Returns the source text corresponding to this [Span]. */ - String get text { - return file.text.substring(start, end); - } - - toMessageString(String message) { - return file.getLocationMessage(message, start, end: end, includeText: true); - } - - int get line { - return file.getLine(start); - } - - int get column { - return file.getColumn(line, start); - } - - int get endLine { - return file.getLine(end); - } - - int get endColumn { - return file.getColumn(endLine, end); - } - - String get locationText { - var line = file.getLine(start); - var column = file.getColumn(line, start); - return '${file.filename}:${line + 1}:${column + 1}'; - } - - /** Compares two source spans by file and position. Handles nulls. */ - int compareTo(SourceSpan other) { - if (file == other.file) { - int d = start - other.start; - return d == 0 ? (end - other.end) : d; - } - return file.compareTo(other.file); - } -} diff --git a/utils/css/token.dart b/utils/css/token.dart deleted file mode 100644 index 144e39c29644..000000000000 --- a/utils/css/token.dart +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -/** - * A single token in the Dart language. - */ -class Token { - /** A member of [TokenKind] specifying what kind of token this is. */ - final int kind; - - /** The [SourceFile] this token came from. */ - final SourceFile source; - - /** The start and end indexes into the [SourceFile] of this [Token]. */ - final int start, end; - - Token(this.kind, this.source, this.start, this.end) {} - - Token.fake(this.kind, span) - : this.source = span.file, this.start = span.start, this.end = span.end; - - /** Returns the source text corresponding to this [Token]. */ - String get text { - return source.text.substring(start, end); - } - - /** Returns a pretty representation of this token for error messages. **/ - String toString() { - var kindText = TokenKind.kindToString(kind); - var actualText = text; - if (kindText != actualText) { - if (actualText.length > 10) { - actualText = actualText.substring(0, 8) + '...'; - } - return '$kindText($actualText)'; - } else { - return kindText; - } - } - - /** Returns a [SourceSpan] representing the source location. */ - SourceSpan get span { - return new SourceSpan(source, start, end); - } -} - -/** A token containing a parsed literal value. */ -class LiteralToken extends Token { - var value; - LiteralToken(kind, source, start, end, this.value) - : super(kind, source, start, end); -} - -/** A token containing error information. */ -class ErrorToken extends Token { - String message; - ErrorToken(kind, source, start, end, this.message) - : super(kind, source, start, end); -} diff --git a/utils/css/tokenizer.dart b/utils/css/tokenizer.dart deleted file mode 100644 index 63573dff140a..000000000000 --- a/utils/css/tokenizer.dart +++ /dev/null @@ -1,315 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -class Tokenizer extends CSSTokenizerBase { - TokenKind cssTokens; - - bool _selectorParsing; - - Tokenizer(SourceFile source, bool skipWhitespace, [int index = 0]) - : super(source, skipWhitespace, index), _selectorParsing = false { - cssTokens = new TokenKind(); - } - - int get startIndex => _startIndex; - - Token next() { - // keep track of our starting position - _startIndex = _index; - - if (_interpStack != null && _interpStack.depth == 0) { - var istack = _interpStack; - _interpStack = _interpStack.pop(); - - /* TODO(terry): Enable for variable and string interpolation. - * if (istack.isMultiline) { - * return finishMultilineStringBody(istack.quote); - * } else { - * return finishStringBody(istack.quote); - * } - */ - } - - int ch; - ch = _nextChar(); - switch(ch) { - case 0: - return _finishToken(TokenKind.END_OF_FILE); - case cssTokens.tokens[TokenKind.SPACE]: - case cssTokens.tokens[TokenKind.TAB]: - case cssTokens.tokens[TokenKind.NEWLINE]: - case cssTokens.tokens[TokenKind.RETURN]: - return finishWhitespace(); - case cssTokens.tokens[TokenKind.END_OF_FILE]: - return _finishToken(TokenKind.END_OF_FILE); - case cssTokens.tokens[TokenKind.AT]: - return _finishToken(TokenKind.AT); - case cssTokens.tokens[TokenKind.DOT]: - int start = _startIndex; // Start where the dot started. - if (maybeEatDigit()) { - // looks like a number dot followed by digit(s). - Token number = finishNumber(); - if (number.kind == TokenKind.INTEGER) { - // It's a number but it's preceeded by a dot, so make it a double. - _startIndex = start; - return _finishToken(TokenKind.DOUBLE); - } else { - // Don't allow dot followed by a double (e.g, '..1'). - return _errorToken(); - } - } else { - // It's really a dot. - return _finishToken(TokenKind.DOT); - } - case cssTokens.tokens[TokenKind.LPAREN]: - return _finishToken(TokenKind.LPAREN); - case cssTokens.tokens[TokenKind.RPAREN]: - return _finishToken(TokenKind.RPAREN); - case cssTokens.tokens[TokenKind.LBRACE]: - return _finishToken(TokenKind.LBRACE); - case cssTokens.tokens[TokenKind.RBRACE]: - return _finishToken(TokenKind.RBRACE); - case cssTokens.tokens[TokenKind.LBRACK]: - return _finishToken(TokenKind.LBRACK); - case cssTokens.tokens[TokenKind.RBRACK]: - return _finishToken(TokenKind.RBRACK); - case cssTokens.tokens[TokenKind.HASH]: - return _finishToken(TokenKind.HASH); - case cssTokens.tokens[TokenKind.PLUS]: - if (maybeEatDigit()) { - return finishNumber(); - } else { - return _finishToken(TokenKind.PLUS); - } - case cssTokens.tokens[TokenKind.MINUS]: - if (maybeEatDigit()) { - return finishNumber(); - } else if (TokenizerHelpers.isIdentifierStart(ch)) { - return this.finishIdentifier(ch); - } else { - return _finishToken(TokenKind.MINUS); - } - case cssTokens.tokens[TokenKind.GREATER]: - return _finishToken(TokenKind.GREATER); - case cssTokens.tokens[TokenKind.TILDE]: - if (_maybeEatChar(cssTokens.tokens[TokenKind.EQUALS])) { - return _finishToken(TokenKind.INCLUDES); // ~= - } else { - return _finishToken(TokenKind.TILDE); - } - case cssTokens.tokens[TokenKind.ASTERISK]: - if (_maybeEatChar(cssTokens.tokens[TokenKind.EQUALS])) { - return _finishToken(TokenKind.SUBSTRING_MATCH); // *= - } else { - return _finishToken(TokenKind.ASTERISK); - } - case cssTokens.tokens[TokenKind.NAMESPACE]: - return _finishToken(TokenKind.NAMESPACE); - case cssTokens.tokens[TokenKind.COLON]: - return _finishToken(TokenKind.COLON); - case cssTokens.tokens[TokenKind.COMMA]: - return _finishToken(TokenKind.COMMA); - case cssTokens.tokens[TokenKind.SEMICOLON]: - return _finishToken(TokenKind.SEMICOLON); - case cssTokens.tokens[TokenKind.PERCENT]: - return _finishToken(TokenKind.PERCENT); - case cssTokens.tokens[TokenKind.SINGLE_QUOTE]: - return _finishToken(TokenKind.SINGLE_QUOTE); - case cssTokens.tokens[TokenKind.DOUBLE_QUOTE]: - return _finishToken(TokenKind.DOUBLE_QUOTE); - case cssTokens.tokens[TokenKind.SLASH]: - if (_maybeEatChar(cssTokens.tokens[TokenKind.ASTERISK])) { - return finishMultiLineComment(); - } else { - return _finishToken(TokenKind.SLASH); - } - case cssTokens.tokens[TokenKind.LESS]: // (CDC). */ - if (_maybeEatChar(cssTokens.tokens[TokenKind.MINUS])) { - if (_maybeEatChar(cssTokens.tokens[TokenKind.GREATER])) { - if (_skipWhitespace) { - return next(); - } else { - return _finishToken(TokenKind.HTML_COMMENT); - } - } - } - } - } - return _errorToken(); - } - -} - -/** Static helper methods. */ -/** Static helper methods. */ -class TokenizerHelpers { - - static bool isIdentifierStart(int c) { - return ((c >= 97/*a*/ && c <= 122/*z*/) || (c >= 65/*A*/ && c <= 90/*Z*/) || - c == 95/*_*/ || c == 45 /*-*/); - } - - static bool isDigit(int c) { - return (c >= 48/*0*/ && c <= 57/*9*/); - } - - static bool isHexDigit(int c) { - return (isDigit(c) || (c >= 97/*a*/ && c <= 102/*f*/) - || (c >= 65/*A*/ && c <= 70/*F*/)); - } - - static bool isIdentifierPart(int c) { - return (isIdentifierStart(c) || isDigit(c) || c == 45 /*-*/); - } -} - diff --git a/utils/css/tokenizer_base.dart b/utils/css/tokenizer_base.dart deleted file mode 100644 index f98f245f910d..000000000000 --- a/utils/css/tokenizer_base.dart +++ /dev/null @@ -1,454 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. -// Generated by scripts/tokenizer_gen.py. - - -abstract class TokenSource { - Token next(); -} - -class InterpStack { - InterpStack next, previous; - final int quote; - final bool isMultiline; - int depth; - - InterpStack(this.previous, this.quote, this.isMultiline): depth = -1; - - InterpStack pop() { - return this.previous; - } - - static InterpStack push(InterpStack stack, int quote, bool isMultiline) { - var newStack = new InterpStack(stack, quote, isMultiline); - if (stack != null) newStack.previous = stack; - return newStack; - } -} - -/** - * The base class for our tokenizer. The hand coded parts are in this file, with - * the generated parts in the subclass Tokenizer. - */ -class CSSTokenizerBase implements TokenSource { - final SourceFile _source; - final bool _skipWhitespace; - String _text; - - int _index; - int _startIndex; - - /** Keeps track of string interpolation state. */ - InterpStack _interpStack; - - CSSTokenizerBase(this._source, this._skipWhitespace, [index = 0]) - : this._index = index { - _text = _source.text; - } - - abstract Token next(); - abstract int getIdentifierKind(); - - int _nextChar() { - if (_index < _text.length) { - return _text.codeUnitAt(_index++); - } else { - return 0; - } - } - - int _peekChar() { - if (_index < _text.length) { - return _text.codeUnitAt(_index); - } else { - return 0; - } - } - - bool _maybeEatChar(int ch) { - if (_index < _text.length) { - if (_text.codeUnitAt(_index) == ch) { - _index++; - return true; - } else { - return false; - } - } else { - return false; - } - } - - String _tokenText() { - if (_index < _text.length) { - return _text.substring(_startIndex, _index); - } else { - return _text.substring(_startIndex, _text.length); - } - } - - Token _finishToken(int kind) { - return new Token(kind, _source, _startIndex, _index); - } - - Token _errorToken([String message = null]) { - return new ErrorToken( - TokenKind.ERROR, _source, _startIndex, _index, message); - } - - Token finishWhitespace() { - _index--; - while (_index < _text.length) { - final ch = _text.codeUnitAt(_index++); - if (ch == 32/*' '*/ || ch == 9/*'\t'*/ || ch == 13/*'\r'*/) { - // do nothing - } else if (ch == 10/*'\n'*/) { - if (!_skipWhitespace) { - return _finishToken(TokenKind.WHITESPACE); // note the newline? - } - } else { - _index--; - if (_skipWhitespace) { - return next(); - } else { - return _finishToken(TokenKind.WHITESPACE); - } - } - - } - return _finishToken(TokenKind.END_OF_FILE); - } - - Token finishSingleLineComment() { - while (true) { - int ch = _nextChar(); - if (ch == 0 || ch == 10/*'\n'*/ || ch == 13/*'\r'*/) { - if (_skipWhitespace) { - return next(); - } else { - return _finishToken(TokenKind.COMMENT); - } - } - } - } - - Token finishMultiLineComment() { - int nesting = 1; - do { - int ch = _nextChar(); - if (ch == 0) { - return _errorToken(); - } else if (ch == 42/*'*'*/) { - if (_maybeEatChar(47/*'/'*/)) { - nesting--; - } - } else if (ch == 47/*'/'*/) { - if (_maybeEatChar(42/*'*'*/)) { - nesting++; - } - } - } while (nesting > 0); - - if (_skipWhitespace) { - return next(); - } else { - return _finishToken(TokenKind.COMMENT); - } - } - - void eatDigits() { - while (_index < _text.length) { - if (TokenizerHelpers.isDigit(_text.codeUnitAt(_index))) { - _index++; - } else { - return; - } - } - } - - static int _hexDigit(int c) { - if(c >= 48/*0*/ && c <= 57/*9*/) { - return c - 48; - } else if (c >= 97/*a*/ && c <= 102/*f*/) { - return c - 87; - } else if (c >= 65/*A*/ && c <= 70/*F*/) { - return c - 55; - } else { - return -1; - } - } - - int readHex([int hexLength]) { - int maxIndex; - if (hexLength == null) { - maxIndex = _text.length - 1; - } else { - // TODO(jimhug): What if this is too long? - maxIndex = _index + hexLength; - if (maxIndex >= _text.length) return -1; - } - var result = 0; - while (_index < maxIndex) { - final digit = _hexDigit(_text.codeUnitAt(_index)); - if (digit == -1) { - if (hexLength == null) { - return result; - } else { - return -1; - } - } - _hexDigit(_text.codeUnitAt(_index)); - // Multiply by 16 rather than shift by 4 since that will result in a - // correct value for numbers that exceed the 32 bit precision of JS - // 'integers'. - // TODO: Figure out a better solution to integer truncation. Issue 638. - result = (result * 16) + digit; - _index++; - } - - return result; - } - - Token finishNumber() { - eatDigits(); - - if (_peekChar() == 46/*.*/) { - // Handle the case of 1.toString(). - _nextChar(); - if (TokenizerHelpers.isDigit(_peekChar())) { - eatDigits(); - return finishNumberExtra(TokenKind.DOUBLE); - } else { - _index--; - } - } - - return finishNumberExtra(TokenKind.INTEGER); - } - - Token finishNumberExtra(int kind) { - if (_maybeEatChar(101/*e*/) || _maybeEatChar(69/*E*/)) { - kind = TokenKind.DOUBLE; - _maybeEatChar(45/*-*/); - _maybeEatChar(43/*+*/); - eatDigits(); - } - if (_peekChar() != 0 && TokenizerHelpers.isIdentifierStart(_peekChar())) { - _nextChar(); - return _errorToken("illegal character in number"); - } - - return _finishToken(kind); - } - - Token _makeStringToken(List buf, bool isPart) { - final s = new String.fromCharCodes(buf); - final kind = isPart ? TokenKind.STRING_PART : TokenKind.STRING; - return new LiteralToken(kind, _source, _startIndex, _index, s); - } - - Token _makeRawStringToken(bool isMultiline) { - String s; - if (isMultiline) { - // Skip initial newline in multiline strings - int start = _startIndex + 4; - if (_source.text[start] == '\n') start++; - s = _source.text.substring(start, _index - 3); - } else { - s = _source.text.substring(_startIndex + 2, _index - 1); - } - return new LiteralToken(TokenKind.STRING, _source, _startIndex, _index, s); - } - - Token finishMultilineString(int quote) { - var buf = []; - while (true) { - int ch = _nextChar(); - if (ch == 0) { - return _errorToken(); - } else if (ch == quote) { - if (_maybeEatChar(quote)) { - if (_maybeEatChar(quote)) { - return _makeStringToken(buf, false); - } - buf.add(quote); - } - buf.add(quote); - } else if (ch == 36/*$*/) { - // start of string interp - _interpStack = InterpStack.push(_interpStack, quote, true); - return _makeStringToken(buf, true); - } else if (ch == 92/*\*/) { - var escapeVal = readEscapeSequence(); - if (escapeVal == -1) { - return _errorToken("invalid hex escape sequence"); - } else { - buf.add(escapeVal); - } - } else { - buf.add(ch); - } - } - } - - Token _finishOpenBrace() { - if (_interpStack != null) { - if (_interpStack.depth == -1) { - _interpStack.depth = 1; - } else { - assert(_interpStack.depth >= 0); - _interpStack.depth += 1; - } - } - return _finishToken(TokenKind.LBRACE); - } - - Token _finishCloseBrace() { - if (_interpStack != null) { - _interpStack.depth -= 1; - assert(_interpStack.depth >= 0); - } - return _finishToken(TokenKind.RBRACE); - } - - Token finishString(int quote) { - if (_maybeEatChar(quote)) { - if (_maybeEatChar(quote)) { - // skip an initial newline - _maybeEatChar(10/*'\n'*/); - return finishMultilineString(quote); - } else { - return _makeStringToken(new List(), false); - } - } - return finishStringBody(quote); - } - - Token finishRawString(int quote) { - if (_maybeEatChar(quote)) { - if (_maybeEatChar(quote)) { - return finishMultilineRawString(quote); - } else { - return _makeStringToken([], false); - } - } - while (true) { - int ch = _nextChar(); - if (ch == quote) { - return _makeRawStringToken(false); - } else if (ch == 0) { - return _errorToken(); - } - } - } - - Token finishMultilineRawString(int quote) { - while (true) { - int ch = _nextChar(); - if (ch == 0) { - return _errorToken(); - } else if (ch == quote && _maybeEatChar(quote) && _maybeEatChar(quote)) { - return _makeRawStringToken(true); - } - } - } - - Token finishStringBody(int quote) { - var buf = new List(); - while (true) { - int ch = _nextChar(); - if (ch == quote) { - return _makeStringToken(buf, false); - } else if (ch == 36/*$*/) { - // start of string interp - _interpStack = InterpStack.push(_interpStack, quote, false); - return _makeStringToken(buf, true); - } else if (ch == 0) { - return _errorToken(); - } else if (ch == 92/*\*/) { - var escapeVal = readEscapeSequence(); - if (escapeVal == -1) { - return _errorToken("invalid hex escape sequence"); - } else { - buf.add(escapeVal); - } - } else { - buf.add(ch); - } - } - } - - int readEscapeSequence() { - final ch = _nextChar(); - int hexValue; - switch (ch) { - case 110/*n*/: - return 0x0a/*'\n'*/; - case 114/*r*/: - return 0x0d/*'\r'*/; - case 102/*f*/: - return 0x0c/*'\f'*/; - case 98/*b*/: - return 0x08/*'\b'*/; - case 116/*t*/: - return 0x09/*'\t'*/; - case 118/*v*/: - return 0x0b/*'\v'*/; - case 120/*x*/: - hexValue = readHex(2); - break; - case 117/*u*/: - if (_maybeEatChar(123/*{*/)) { - hexValue = readHex(); - if (!_maybeEatChar(125/*}*/)) { - return -1; - } else { - break; - } - } else { - hexValue = readHex(4); - break; - } - default: return ch; - } - - if (hexValue == -1) return -1; - - // According to the Unicode standard the high and low surrogate halves - // used by UTF-16 (U+D800 through U+DFFF) and values above U+10FFFF - // are not legal Unicode values. - if (hexValue < 0xD800 || hexValue > 0xDFFF && hexValue <= 0xFFFF) { - return hexValue; - } else if (hexValue <= 0x10FFFF){ - world.fatal('unicode values greater than 2 bytes not implemented yet'); - return -1; - } else { - return -1; - } - } - - Token finishDot() { - if (TokenizerHelpers.isDigit(_peekChar())) { - eatDigits(); - return finishNumberExtra(TokenKind.DOUBLE); - } else { - return _finishToken(TokenKind.DOT); - } - } - - Token finishIdentifier(int ch) { - while (_index < _text.length) { - if (!TokenizerHelpers.isIdentifierPart(_text.codeUnitAt(_index++))) { - _index--; - break; - } - } - int kind = getIdentifierKind(); - if (kind == TokenKind.IDENTIFIER) { - return _finishToken(TokenKind.IDENTIFIER); - } else { - return _finishToken(kind); - } - } -} - diff --git a/utils/css/tokenkind.dart b/utils/css/tokenkind.dart deleted file mode 100644 index fbcebdf09573..000000000000 --- a/utils/css/tokenkind.dart +++ /dev/null @@ -1,596 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -// TODO(terry): Need to be consistent with tokens either they're ASCII tokens -// e.g., ASTERISK or they're CSS e.g., PSEUDO, COMBINATOR_*. -class TokenKind { - // Common shared tokens used in TokenizerBase. - static const int UNUSED = 0; // Unused place holder... - static const int END_OF_FILE = 1; // TODO(terry): Must match base - static const int LPAREN = 2; // ( - static const int RPAREN = 3; // ) - static const int LBRACK = 4; // [ - static const int RBRACK = 5; // ] - static const int LBRACE = 6; // { - static const int RBRACE = 7; // } - static const int DOT = 8; // . - static const int SEMICOLON = 9; // ; - - // Unique tokens for CSS. - static const int AT = 10; // @ - static const int HASH = 11; // # - static const int PLUS = 12; // + - static const int GREATER = 13; // > - static const int TILDE = 14; // ~ - static const int ASTERISK = 15; // * - static const int NAMESPACE = 16; // | - static const int COLON = 17; // : - static const int PRIVATE_NAME = 18; // _ prefix private class or id - static const int COMMA = 19; // , - static const int SPACE = 20; - static const int TAB = 21; // /t - static const int NEWLINE = 22; // /n - static const int RETURN = 23; // /r - static const int PERCENT = 24; // % - static const int SINGLE_QUOTE = 25; // ' - static const int DOUBLE_QUOTE = 26; // " - static const int SLASH = 27; // / - static const int EQUALS = 28; // = - static const int OR = 29; // | - static const int CARET = 30; // ^ - static const int DOLLAR = 31; // $ - static const int LESS = 32; // < - static const int BANG = 33; // ! - static const int MINUS = 34; // - - - // WARNING: END_TOKENS must be 1 greater than the last token above (last - // character in our list). Also add to kindToString function and the - // constructor for TokenKind. - - static const int END_TOKENS = 35; // Marker for last token in list - - /** [TokenKind] representing integer tokens. */ - static const int INTEGER = 60; // TODO(terry): must match base - - /** [TokenKind] representing hex integer tokens. */ -// static const int HEX_INTEGER = 61; // TODO(terry): must match base - - /** [TokenKind] representing double tokens. */ - static const int DOUBLE = 62; // TODO(terry): must match base - - /** [TokenKind] representing whitespace tokens. */ - static const int WHITESPACE = 63; // TODO(terry): must match base - - /** [TokenKind] representing comment tokens. */ - static const int COMMENT = 64; // TODO(terry): must match base - - /** [TokenKind] representing error tokens. */ - static const int ERROR = 65; // TODO(terry): must match base - - /** [TokenKind] representing incomplete string tokens. */ - static const int INCOMPLETE_STRING = 66; // TODO(terry): must match base - - /** [TokenKind] representing incomplete comment tokens. */ - static const int INCOMPLETE_COMMENT = 67; // TODO(terry): must match base - - // Synthesized Tokens (no character associated with TOKEN). - // TODO(terry): Possible common names used by both Dart and CSS tokenizers. - static const int STRING = 500; - static const int STRING_PART = 501; - static const int NUMBER = 502; - static const int HEX_NUMBER = 503; - static const int HTML_COMMENT = 504; // ). -class CommentDefinition extends CssComment { - CommentDefinition(String comment, SourceSpan span): super(comment, span); - - visit(TreeVisitor visitor) => visitor.visitCommentDefinition(this); - - String toString() => ''; -} - -class SelectorGroup extends ASTNode { - List _selectors; - - SelectorGroup(this._selectors, SourceSpan span): super(span); - - List get selectors => _selectors; - - visit(TreeVisitor visitor) => visitor.visitSelectorGroup(this); - - String toString() { - StringBuffer buff = new StringBuffer(); - int idx = 0; - for (final selector in _selectors) { - if (idx++ > 0) { - buff.write(', '); - } - buff.write(selector.toString()); - } - return buff.toString(); - } - - /** A multiline string showing the node and its children. */ - String toDebugString() { - var to = new TreeOutput(); - var tp = new TreePrinter(to); - this.visit(tp); - return to.buf.toString(); - } -} - -class Selector extends ASTNode { - List _simpleSelectorSequences; - - Selector(this._simpleSelectorSequences, SourceSpan span) : super(span); - - List get simpleSelectorSequences => - _simpleSelectorSequences; - - add(SimpleSelectorSequence seq) => _simpleSelectorSequences.add(seq); - - List get simpleSelectorSquences => - _simpleSelectorSequences; - - int get length => _simpleSelectorSequences.length; - - String toString() { - StringBuffer buff = new StringBuffer(); - for (final simpleSelectorSequence in _simpleSelectorSequences) { - buff.write(simpleSelectorSequence.toString()); - } - return buff.toString(); - } - - visit(TreeVisitor visitor) => visitor.visitSelector(this); -} - -class SimpleSelectorSequence extends ASTNode { - int _combinator; // +, >, ~, NONE - SimpleSelector _selector; - - SimpleSelectorSequence(this._selector, SourceSpan span, - [this._combinator = TokenKind.COMBINATOR_NONE]) : super(span); - - get simpleSelector => _selector; - - bool isCombinatorNone() => _combinator == TokenKind.COMBINATOR_NONE; - bool isCombinatorPlus() => _combinator == TokenKind.COMBINATOR_PLUS; - bool isCombinatorGreater() => _combinator == TokenKind.COMBINATOR_GREATER; - bool isCombinatorTilde() => _combinator == TokenKind.COMBINATOR_TILDE; - bool isCombinatorDescendant() => - _combinator == TokenKind.COMBINATOR_DESCENDANT; - - String _combinatorToString() => - isCombinatorDescendant() ? ' ' : - isCombinatorPlus() ? '+' : - isCombinatorGreater() ? '>' : - isCombinatorTilde() ? '~' : ''; - - visit(TreeVisitor visitor) => visitor.visitSimpleSelectorSequence(this); - - String toString() => "${_combinatorToString()}${_selector.toString()}"; -} - -/* All other selectors (element, #id, .class, attribute, pseudo, negation, - * namespace, *) are derived from this selector. - */ -class SimpleSelector extends ASTNode { - var _name; - - SimpleSelector(this._name, SourceSpan span) : super(span); - - // Name can be an Identifier or WildCard we'll return either the name or '*'. - String get name => isWildcard() ? '*' : _name.name; - - bool isWildcard() => _name is Wildcard; - - visit(TreeVisitor visitor) => visitor.visitSimpleSelector(this); - - String toString() => name; -} - -// element name -class ElementSelector extends SimpleSelector { - ElementSelector(var name, SourceSpan span) : super(name, span); - - visit(TreeVisitor visitor) => visitor.visitElementSelector(this); - - String toString() => "$name"; - - /** A multiline string showing the node and its children. */ - String toDebugString() { - var to = new TreeOutput(); - var tp = new TreePrinter(to); - this.visit(tp); - return to.buf.toString(); - } -} - -// namespace|element -class NamespaceSelector extends SimpleSelector { - var _namespace; // null, Wildcard or Identifier - - NamespaceSelector(this._namespace, var name, SourceSpan span) : - super(name, span); - - String get namespace => _namespace is Wildcard ? '*' : _namespace.name; - - bool isNamespaceWildcard() => _namespace is Wildcard; - - SimpleSelector get nameAsSimpleSelector => _name; - - visit(TreeVisitor visitor) => visitor.visitNamespaceSelector(this); - - String toString() => "$namespace|${nameAsSimpleSelector.name}"; -} - -// [attr op value] -class AttributeSelector extends SimpleSelector { - int _op; - var _value; - - AttributeSelector(Identifier name, this._op, this._value, - SourceSpan span) : super(name, span); - - String matchOperator() { - switch (_op) { - case TokenKind.EQUALS: - return '='; - case TokenKind.INCLUDES: - return '~='; - case TokenKind.DASH_MATCH: - return '|='; - case TokenKind.PREFIX_MATCH: - return '^='; - case TokenKind.SUFFIX_MATCH: - return '\$='; - case TokenKind.SUBSTRING_MATCH: - return '*='; - } - } - - // Return the TokenKind for operator used by visitAttributeSelector. - String matchOperatorAsTokenString() { - switch (_op) { - case TokenKind.EQUALS: - return 'EQUALS'; - case TokenKind.INCLUDES: - return 'INCLUDES'; - case TokenKind.DASH_MATCH: - return 'DASH_MATCH'; - case TokenKind.PREFIX_MATCH: - return 'PREFIX_MATCH'; - case TokenKind.SUFFIX_MATCH: - return 'SUFFIX_MATCH'; - case TokenKind.SUBSTRING_MATCH: - return 'SUBSTRING_MATCH'; - } - } - - String valueToString() { - if (_value is Identifier) { - return _value.name; - } else { - return '"${_value}"'; - } - } - - visit(TreeVisitor visitor) => visitor.visitAttributeSelector(this); - - String toString() => "[${name} ${matchOperator()} ${valueToString()}]"; -} - -// #id -class IdSelector extends SimpleSelector { - IdSelector(Identifier name, SourceSpan span) : super(name, span); - - visit(TreeVisitor visitor) => visitor.visitIdSelector(this); - - String toString() => "#$name"; -} - -// .class -class ClassSelector extends SimpleSelector { - ClassSelector(Identifier name, SourceSpan span) : super(name, span); - - visit(TreeVisitor visitor) => visitor.visitClassSelector(this); - - String toString() => ".$name"; -} - -// :pseudoClass -class PseudoClassSelector extends SimpleSelector { - PseudoClassSelector(Identifier name, SourceSpan span) : - super(name, span); - - visit(TreeVisitor visitor) => visitor.visitPseudoClassSelector(this); - - String toString() => ":$name"; -} - -// ::pseudoElement -class PseudoElementSelector extends SimpleSelector { - PseudoElementSelector(Identifier name, SourceSpan span) : - super(name, span); - - visit(TreeVisitor visitor) => visitor.visitPseudoElementSelector(this); - - String toString() => "::$name"; -} - -// TODO(terry): Implement -// NOT -class NotSelector extends SimpleSelector { - NotSelector(String name, SourceSpan span) : super(name, span); - - visit(TreeVisitor visitor) => visitor.visitNotSelector(this); -} - -class Stylesheet extends ASTNode { - // Contains charset, ruleset, directives (media, page, etc.) - List _topLevels; - - Stylesheet(this._topLevels, SourceSpan span) : super(span) { - for (final node in _topLevels) { - assert(node is TopLevelProduction || node is Directive); - } - } - - visit(TreeVisitor visitor) => visitor.visitStylesheet(this); - - List get topLevels => _topLevels; - - String toString() { - StringBuffer buff = new StringBuffer(); - for (final topLevel in _topLevels) { - buff.write(topLevel.toString()); - } - return buff.toString(); - } - - /** A multiline string showing the node and its children. */ - String toDebugString() { - var to = new TreeOutput(); - var tp = new TreePrinter(to); - this.visit(tp); - return to.buf.toString(); - } -} - -class TopLevelProduction extends ASTNode { - TopLevelProduction(SourceSpan span) : super(span); - - visit(TreeVisitor visitor) => visitor.visitTopLevelProduction(this); - - String toString() => "TopLevelProduction"; -} - -class RuleSet extends TopLevelProduction { - SelectorGroup _selectorGroup; - DeclarationGroup _declarationGroup; - - RuleSet(this._selectorGroup, this._declarationGroup, SourceSpan span) : - super(span); - - SelectorGroup get selectorGroup => _selectorGroup; - DeclarationGroup get declarationGroup => _declarationGroup; - - visit(TreeVisitor visitor) => visitor.visitRuleSet(this); - - String toString() => - "\n${_selectorGroup.toString()} {\n" - "${_declarationGroup.toString()}}\n"; -} - -class Directive extends ASTNode { - Directive(SourceSpan span) : super(span); - - String toString() => "Directive"; - - bool get isBuiltIn => true; // Known CSS directive? - bool get isExtension => false; // SCSS extension? - - visit(TreeVisitor visitor) => visitor.visitDirective(this); -} - -class ImportDirective extends Directive { - String _import; - List _media; - - ImportDirective(this._import, this._media, SourceSpan span) : - super(span); - - visit(TreeVisitor visitor) => visitor.visitImportDirective(this); - - String toString() { - StringBuffer buff = new StringBuffer(); - - buff.write('@import url(${_import})'); - - int idx = 0; - for (final medium in _media) { - buff.write(idx++ == 0 ? ' $medium' : ',$medium'); - } - buff.write('\n'); - - return buff.toString(); - } -} - -class MediaDirective extends Directive { - List _media; - RuleSet _ruleset; - - MediaDirective(this._media, this._ruleset, SourceSpan span) : - super(span); - - visit(TreeVisitor visitor) => visitor.visitMediaDirective(this); - - String toString() { - StringBuffer buff = new StringBuffer(); - - buff.write('@media'); - int idx = 0; - for (var medium in _media) { - buff.write(idx++ == 0 ? ' $medium' : ',$medium'); - } - buff.write(' {\n'); - buff.write(_ruleset.toString()); - buff.write('\n\}\n'); - - return buff.toString(); - } -} - -class PageDirective extends Directive { - String _pseudoPage; - DeclarationGroup _decls; - - PageDirective(this._pseudoPage, this._decls, SourceSpan span) : - super(span); - - visit(TreeVisitor visitor) => visitor.visitPageDirective(this); - - // @page : pseudoPage { - // decls - // } - String toString() { - StringBuffer buff = new StringBuffer(); - - buff.write('@page '); - if (_pseudoPage != null) { - buff.write(': ${_pseudoPage} '); - } - buff.write('{\n${_decls.toString()}\n}\n'); - - return buff.toString(); - } -} - -class KeyFrameDirective extends Directive { - var _name; - List _blocks; - - KeyFrameDirective(this._name, SourceSpan span) : - _blocks = [], super(span); - - add(KeyFrameBlock block) { - _blocks.add(block); - } - - String get name => _name; - - visit(TreeVisitor visitor) => visitor.visitKeyFrameDirective(this); - - String toString() { - StringBuffer buff = new StringBuffer(); - buff.write('@-webkit-keyframes ${_name} {\n'); - for (final block in _blocks) { - buff.write(block.toString()); - } - buff.write('}\n'); - return buff.toString(); - } -} - -class KeyFrameBlock extends Expression { - Expressions _blockSelectors; - DeclarationGroup _declarations; - - KeyFrameBlock(this._blockSelectors, this._declarations, SourceSpan span): - super(span); - - visit(TreeVisitor visitor) => visitor.visitKeyFrameBlock(this); - - String toString() { - StringBuffer buff = new StringBuffer(); - buff.write(' ${_blockSelectors.toString()} {\n'); - buff.write(_declarations.toString()); - buff.write(' }\n'); - return buff.toString(); - } -} - -// TODO(terry): TBD -class FontFaceDirective extends Directive { - List _declarations; - - FontFaceDirective(this._declarations, SourceSpan span) : super(span); - - visit(TreeVisitor visitor) => visitor.visitFontFaceDirective(this); - - String toString() { - return "TO BE DONE"; - } -} - -class IncludeDirective extends Directive { - String _include; - Stylesheet _stylesheet; - - IncludeDirective(this._include, this._stylesheet, SourceSpan span) : - super(span); - - visit(TreeVisitor visitor) => visitor.visitIncludeDirective(this); - - bool get isBuiltIn => false; - bool get isExtension => true; - - Stylesheet get styleSheet => _stylesheet; - - String toString() { - StringBuffer buff = new StringBuffer(); - buff.write('/****** @include ${_include} ******/\n'); - buff.write(_stylesheet != null ? _stylesheet.toString() : '// '); - buff.write('/****** End of ${_include} ******/\n\n'); - return buff.toString(); - } -} - -class StyletDirective extends Directive { - String _dartClassName; - List _rulesets; - - StyletDirective(this._dartClassName, this._rulesets, SourceSpan span) : - super(span); - - bool get isBuiltIn => false; - bool get isExtension => true; - - String get dartClassName => _dartClassName; - List get rulesets => _rulesets; - - visit(TreeVisitor visitor) => visitor.visitStyletDirective(this); - - // TODO(terry): Output Dart class - String toString() => '/* @stylet export as ${_dartClassName} */\n'; -} - -class Declaration extends ASTNode { - Identifier _property; - Expression _expression; - bool _important; - - Declaration(this._property, this._expression, SourceSpan span) : - _important = false, super(span); - - String get property => _property.name; - Expression get expression => _expression; - - bool get important => _important; - set important(bool value) => _important = value; - String importantAsString() => _important ? ' !important' : ''; - - visit(TreeVisitor visitor) => visitor.visitDeclaration(this); - - String toString() => - "${_property.name}: ${_expression.toString()}${importantAsString()}"; -} - -class DeclarationGroup extends ASTNode { - List _declarations; - - DeclarationGroup(this._declarations, SourceSpan span) : super(span); - - List get declarations => _declarations; - - visit(TreeVisitor visitor) => visitor.visitDeclarationGroup(this); - - String toString() { - StringBuffer buff = new StringBuffer(); - int idx = 0; - for (final declaration in _declarations) { - buff.write(" ${declaration.toString()};\n"); - } - return buff.toString(); - } -} - -class OperatorSlash extends Expression { - OperatorSlash(SourceSpan span) : super(span); - - visit(TreeVisitor visitor) => visitor.visitOperatorSlash(this); - - String toString() => ' /'; -} - -class OperatorComma extends Expression { - OperatorComma(SourceSpan span) : super(span); - - visit(TreeVisitor visitor) => visitor.visitOperatorComma(this); - - String toString() => ','; -} - -class LiteralTerm extends Expression { - var _value; - String _text; - - LiteralTerm(this._value, this._text, SourceSpan span) : super(span); - - get value => _value; - String get text => _text; - - visit(TreeVisitor visitor) => visitor.visitLiteralTerm(this); - - String toString() => _text; -} - -class NumberTerm extends LiteralTerm { - NumberTerm(var value, String t, SourceSpan span) : super(value, t, span); - - visit(TreeVisitor visitor) => visitor.visitNumberTerm(this); -} - -class UnitTerm extends LiteralTerm { - int _unit; - - UnitTerm(var value, String t, SourceSpan span, this._unit) : - super(value, t, span); - - int get unit => _unit; - - visit(TreeVisitor visitor) => visitor.visitUnitTerm(this); - - String toString() => '${text}${unitToString()}'; - String unitToString() => TokenKind.unitToString(_unit); -} - -class LengthTerm extends UnitTerm { - LengthTerm(var value, String t, SourceSpan span, - [int unit = TokenKind.UNIT_LENGTH_PX]) : super(value, t, span, unit) { - assert(this._unit == TokenKind.UNIT_LENGTH_PX || - this._unit == TokenKind.UNIT_LENGTH_CM || - this._unit == TokenKind.UNIT_LENGTH_MM || - this._unit == TokenKind.UNIT_LENGTH_IN || - this._unit == TokenKind.UNIT_LENGTH_PT || - this._unit == TokenKind.UNIT_LENGTH_PC); - } - - visit(TreeVisitor visitor) => visitor.visitLengthTerm(this); -} - -class PercentageTerm extends LiteralTerm { - PercentageTerm(var value, String t, SourceSpan span) : - super(value, t, span); - - visit(TreeVisitor visitor) => visitor.visitPercentageTerm(this); - - String toString() => '${text}%'; - -} - -class EmTerm extends LiteralTerm { - EmTerm(var value, String t, SourceSpan span) : - super(value, t, span); - - visit(TreeVisitor visitor) => visitor.visitEmTerm(this); - - String toString() => '${text}em'; -} - -class ExTerm extends LiteralTerm { - ExTerm(var value, String t, SourceSpan span) : - super(value, t, span); - - visit(TreeVisitor visitor) => visitor.visitExTerm(this); - - String toString() => '${text}ex'; -} - -class AngleTerm extends UnitTerm { - AngleTerm(var value, String t, SourceSpan span, - [int unit = TokenKind.UNIT_LENGTH_PX]) : super(value, t, span, unit) { - assert(this._unit == TokenKind.UNIT_ANGLE_DEG || - this._unit == TokenKind.UNIT_ANGLE_RAD || - this._unit == TokenKind.UNIT_ANGLE_GRAD); - } - - visit(TreeVisitor visitor) => visitor.visitAngleTerm(this); -} - -class TimeTerm extends UnitTerm { - TimeTerm(var value, String t, SourceSpan span, - [int unit = TokenKind.UNIT_LENGTH_PX]) : super(value, t, span, unit) { - assert(this._unit == TokenKind.UNIT_ANGLE_DEG || - this._unit == TokenKind.UNIT_TIME_MS || - this._unit == TokenKind.UNIT_TIME_S); - } - - visit(TreeVisitor visitor) => visitor.visitTimeTerm(this); -} - -class FreqTerm extends UnitTerm { - FreqTerm(var value, String t, SourceSpan span, - [int unit = TokenKind.UNIT_LENGTH_PX]) : super(value, t, span, unit) { - assert(_unit == TokenKind.UNIT_FREQ_HZ || _unit == TokenKind.UNIT_FREQ_KHZ); - } - - visit(TreeVisitor visitor) => visitor.visitFreqTerm(this); -} - -class FractionTerm extends LiteralTerm { - FractionTerm(var value, String t, SourceSpan span) : - super(value, t, span); - - visit(TreeVisitor visitor) => visitor.visitFractionTerm(this); - - String toString() => '${text}fr'; -} - -class UriTerm extends LiteralTerm { - UriTerm(String value, SourceSpan span) : super(value, value, span); - - visit(TreeVisitor visitor) => visitor.visitUriTerm(this); - - String toString() => 'url(${text})'; -} - -class HexColorTerm extends LiteralTerm { - HexColorTerm(var value, String t, SourceSpan span) : - super(value, t, span); - - visit(TreeVisitor visitor) => visitor.visitHexColorTerm(this); - - String toString() => '#${text}'; -} - -class FunctionTerm extends LiteralTerm { - Expressions _params; - - FunctionTerm(var value, String t, this._params, SourceSpan span) - : super(value, t, span); - - visit(TreeVisitor visitor) => visitor.visitFunctionTerm(this); - - String toString() { - // TODO(terry): Optimize rgb to a hexcolor. - StringBuffer buff = new StringBuffer(); - - buff.write('${text}('); - buff.write(_params.toString()); - buff.write(')'); - - return buff.toString(); - } -} - -class GroupTerm extends Expression { - List _terms; - - GroupTerm(SourceSpan span) : _terms = [], super(span); - - add(LiteralTerm term) { - _terms.add(term); - } - - visit(TreeVisitor visitor) => visitor.visitGroupTerm(this); - - String toString() { - StringBuffer buff = new StringBuffer(); - buff.write('('); - int idx = 0; - for (final term in _terms) { - if (idx++ > 0) { - buff.write(' '); - } - buff.write(term.toString()); - } - buff.write(')'); - return buff.toString(); - } -} - -class ItemTerm extends NumberTerm { - ItemTerm(var value, String t, SourceSpan span) : super(value, t, span); - - visit(TreeVisitor visitor) => visitor.visitItemTerm(this); - - String toString() => '[${text}]'; -} - -class Expressions extends Expression { - List _expressions; - - Expressions(SourceSpan span): super(span), _expressions = []; - - add(Expression expression) { - _expressions.add(expression); - } - - List get expressions => _expressions; - - visit(TreeVisitor visitor) => visitor.visitExpressions(this); - - String toString() { - StringBuffer buff = new StringBuffer(); - int idx = 0; - for (final expression in _expressions) { - // Add space seperator between terms without an operator. - // TODO(terry): Should have a BinaryExpression to solve this problem. - if (idx > 0 && - !(expression is OperatorComma || expression is OperatorSlash)) { - buff.write(' '); - } - buff.write(expression.toString()); - idx++; - } - return buff.toString(); - } -} - -class BinaryExpression extends Expression { - Token op; - Expression x; - Expression y; - - BinaryExpression(this.op, this.x, this.y, SourceSpan span): super(span); - - visit(TreeVisitor visitor) => visitor.visitBinaryExpression(this); -} - -class UnaryExpression extends Expression { - Token op; - Expression self; - - UnaryExpression(this.op, this.self, SourceSpan span): super(span); - - visit(TreeVisitor visitor) => visitor.visitUnaryExpression(this); -} - -abstract class TreeVisitor { - void visitCssComment(CssComment node); - void visitCommentDefinition(CommentDefinition node); - void visitStylesheet(Stylesheet node); - void visitTopLevelProduction(TopLevelProduction node); - void visitDirective(Directive node); - void visitMediaDirective(MediaDirective node); - void visitPageDirective(PageDirective node); - void visitImportDirective(ImportDirective node); - void visitKeyFrameDirective(KeyFrameDirective node); - void visitKeyFrameBlock(KeyFrameBlock node); - void visitFontFaceDirective(FontFaceDirective node); - void visitIncludeDirective(IncludeDirective node); - void visitStyletDirective(StyletDirective node); - - void visitRuleSet(RuleSet node); - void visitDeclarationGroup(DeclarationGroup node); - void visitDeclaration(Declaration node); - void visitSelectorGroup(SelectorGroup node); - void visitSelector(Selector node); - void visitSimpleSelectorSequence(SimpleSelectorSequence node); - void visitSimpleSelector(SimpleSelector node); - void visitElementSelector(ElementSelector node); - void visitNamespaceSelector(NamespaceSelector node); - void visitAttributeSelector(AttributeSelector node); - void visitIdSelector(IdSelector node); - void visitClassSelector(ClassSelector node); - void visitPseudoClassSelector(PseudoClassSelector node); - void visitPseudoElementSelector(PseudoElementSelector node); - void visitNotSelector(NotSelector node); - - void visitLiteralTerm(LiteralTerm node); - void visitHexColorTerm(HexColorTerm node); - void visitNumberTerm(NumberTerm node); - void visitUnitTerm(UnitTerm node); - void visitLengthTerm(LengthTerm node); - void visitPercentageTerm(PercentageTerm node); - void visitEmTerm(EmTerm node); - void visitExTerm(ExTerm node); - void visitAngleTerm(AngleTerm node); - void visitTimeTerm(TimeTerm node); - void visitFreqTerm(FreqTerm node); - void visitFractionTerm(FractionTerm node); - void visitUriTerm(UriTerm node); - void visitFunctionTerm(FunctionTerm node); - void visitGroupTerm(GroupTerm node); - void visitItemTerm(ItemTerm node); - void visitOperatorSlash(OperatorSlash node); - void visitOperatorComma(OperatorComma node); - - void visitExpressions(Expressions node); - void visitBinaryExpression(BinaryExpression node); - void visitUnaryExpression(UnaryExpression node); - - void visitIdentifier(Identifier node); - void visitWildcard(Wildcard node); - - // TODO(terry): Defined for ../tree.dart. - void visitTypeReference(TypeReference node); -} - -class TreePrinter implements TreeVisitor { - var output; - TreePrinter(this.output) { output.printer = this; } - - void visitStylesheet(Stylesheet node) { - output.heading('Stylesheet', node.span); - output.depth++; - output.writeNodeList('productions', node._topLevels); - output.depth--; - } - - void visitTopLevelProduction(TopLevelProduction node) { - output.heading('TopLevelProduction', node.span); - } - - void visitDirective(Directive node) { - output.heading('Directive', node.span); - } - - void visitCssComment(CssComment node) { - output.heading('Comment', node.span); - output.depth++; - output.writeValue('comment value', node.comment); - output.depth--; - } - - void visitCommentDefinition(CommentDefinition node) { - output.heading('CommentDefinition (CDO/CDC)', node.span); - output.depth++; - output.writeValue('comment value', node.comment); - output.depth--; - } - - void visitMediaDirective(MediaDirective node) { - output.heading('MediaDirective', node.span); - output.depth++; - output.writeNodeList('media', node._media); - visitRuleSet(node._ruleset); - output.depth--; - } - - void visitPageDirective(PageDirective node) { - output.heading('PageDirective', node.span); - output.depth++; - output.writeValue('pseudo page', node._pseudoPage); - visitDeclarationGroup(node._decls); - output.depth; -} - - void visitImportDirective(ImportDirective node) { - output.heading('ImportDirective', node.span); - output.depth++; - output.writeValue('import', node._import); - output.writeNodeList('media', node._media); - output.depth--; - } - - void visitKeyFrameDirective(KeyFrameDirective node) { - output.heading('KeyFrameDirective', node.span); - output.depth++; - output.writeValue('name', node._name); - output.writeNodeList('blocks', node._blocks); - output.depth--; - } - - void visitKeyFrameBlock(KeyFrameBlock node) { - output.heading('KeyFrameBlock', node.span); - output.depth++; - visitExpressions(node._blockSelectors); - visitDeclarationGroup(node._declarations); - output.depth--; - } - - void visitFontFaceDirective(FontFaceDirective node) { - // TODO(terry): To Be Implemented - } - - void visitIncludeDirective(IncludeDirective node) { - output.heading('IncludeDirective', node.span); - output.writeValue('include', node._include); - output.depth++; - if (node._stylesheet != null) { - visitStylesheet(node._stylesheet); - } else { - output.writeValue('StyleSheet', ''); - } - output.depth--; - } - - void visitStyletDirective(StyletDirective node) { - output.heading('StyletDirective', node.span); - output.writeValue('dartClassName', node._dartClassName); - output.depth++; - output.writeNodeList('rulesets', node._rulesets); - output.depth--; -} - - void visitRuleSet(RuleSet node) { - output.heading('Ruleset', node.span); - output.depth++; - visitSelectorGroup(node._selectorGroup); - visitDeclarationGroup(node._declarationGroup); - output.depth--; - } - - void visitDeclarationGroup(DeclarationGroup node) { - output.heading('DeclarationGroup', node.span); - output.depth++; - output.writeNodeList('declarations', node._declarations); - output.depth--; - } - - void visitDeclaration(Declaration node) { - output.heading('Declaration', node.span); - output.depth++; - output.write('property'); - visitIdentifier(node._property); - output.writeNode('expression', node._expression); - if (node.important) { - output.writeValue('!important', 'true'); - } - output.depth--; - } - - void visitSelectorGroup(SelectorGroup node) { - output.heading('Selector Group', node.span); - output.depth++; - output.writeNodeList('selectors', node.selectors); - output.depth--; - } - - void visitSelector(Selector node) { - output.heading('Selector', node.span); - output.depth++; - output.writeNodeList('simpleSelectorsSequences', - node._simpleSelectorSequences); - output.depth--; - } - - void visitSimpleSelectorSequence(SimpleSelectorSequence node) { - output.heading('SimpleSelectorSequence', node.span); - output.depth++; - if (node.isCombinatorNone()) { - output.writeValue('combinator', "NONE"); - } else if (node.isCombinatorDescendant()) { - output.writeValue('combinator', "descendant"); - } else if (node.isCombinatorPlus()) { - output.writeValue('combinator', "+"); - } else if (node.isCombinatorGreater()) { - output.writeValue('combinator', ">"); - } else if (node.isCombinatorTilde()) { - output.writeValue('combinator', "~"); - } else { - output.writeValue('combinator', "ERROR UNKNOWN"); - } - - var selector = node._selector; - if (selector is NamespaceSelector) { - visitNamespaceSelector(selector); - } else if (selector is ElementSelector) { - visitElementSelector(selector); - } else if (selector is IdSelector) { - visitIdSelector(selector); - } else if (selector is ClassSelector) { - visitClassSelector(selector); - } else if (selector is PseudoClassSelector) { - visitPseudoClassSelector(selector); - } else if (selector is PseudoElementSelector) { - visitPseudoElementSelector(selector); - } else if (selector is NotSelector) { - visitNotSelector(selector); - } else if (selector is AttributeSelector) { - visitAttributeSelector(selector); - } else { - output.heading('SimpleSelector', selector.span); - output.depth++; - visitSimpleSelector(selector); - output.depth--; - } - - output.depth--; - } - - void visitSimpleSelector(SimpleSelector node) { - visitIdentifier(node._name); - } - - void visitNamespaceSelector(NamespaceSelector node) { - output.heading('Namespace Selector', node.span); - output.depth++; - - var namespace = node._namespace; - if (namespace is Identifier) { - visitIdentifier(namespace); - } else if (namespace is Wildcard) { - visitWildcard(namespace); - } else { - output.writeln("NULL"); - } - - visitSimpleSelector(node.nameAsSimpleSelector); - output.depth--; - } - - void visitElementSelector(ElementSelector node) { - output.heading('Element Selector', node.span); - output.depth++; - visitSimpleSelector(node); - output.depth--; - } - - void visitAttributeSelector(AttributeSelector node) { - output.heading('AttributeSelector', node.span); - output.depth++; - visitSimpleSelector(node); - String tokenStr = node.matchOperatorAsTokenString(); - output.writeValue('operator', '${node.matchOperator()} (${tokenStr})'); - output.writeValue('value', node.valueToString()); - output.depth--; - } - - void visitIdSelector(IdSelector node) { - output.heading('Id Selector', node.span); - output.depth++; - visitSimpleSelector(node); - output.depth--; - } - - void visitClassSelector(ClassSelector node) { - output.heading('Class Selector', node.span); - output.depth++; - visitSimpleSelector(node); - output.depth--; - } - - void visitPseudoClassSelector(PseudoClassSelector node) { - output.heading('Pseudo Class Selector', node.span); - output.depth++; - visitSimpleSelector(node); - output.depth--; - } - - void visitPseudoElementSelector(PseudoElementSelector node) { - output.heading('Pseudo Element Selector', node.span); - output.depth++; - visitSimpleSelector(node); - output.depth--; - } - - void visitNotSelector(NotSelector node) { - visitSimpleSelector(node); - output.depth++; - output.heading('Not Selector', node.span); - output.depth--; - } - - void visitLiteralTerm(LiteralTerm node) { - output.heading('LiteralTerm', node.span); - output.depth++; - output.writeValue('value', node.text); - output.depth--; - } - - void visitHexColorTerm(HexColorTerm node) { - output.heading('HexColorTerm', node.span); - output.depth++; - output.writeValue('hex value', node.text); - output.writeValue('decimal value', node.value); - output.depth--; - } - - void visitNumberTerm(NumberTerm node) { - output.heading('NumberTerm', node.span); - output.depth++; - output.writeValue('value', node.text); - output.depth--; - } - - void visitUnitTerm(UnitTerm node) { - String unitValue; - - output.depth++; - output.writeValue('value', node.text); - output.writeValue('unit', node.unitToString()); - output.depth--; - } - - void visitLengthTerm(LengthTerm node) { - output.heading('LengthTerm', node.span); - visitUnitTerm(node); - } - - void visitPercentageTerm(PercentageTerm node) { - output.heading('PercentageTerm', node.span); - output.depth++; - visitLiteralTerm(node); - output.depth--; - } - - void visitEmTerm(EmTerm node) { - output.heading('EmTerm', node.span); - output.depth++; - visitLiteralTerm(node); - output.depth--; - } - - void visitExTerm(ExTerm node) { - output.heading('ExTerm', node.span); - output.depth++; - visitLiteralTerm(node); - output.depth--; - } - - void visitAngleTerm(AngleTerm node) { - output.heading('AngleTerm', node.span); - visitUnitTerm(node); - } - - void visitTimeTerm(TimeTerm node) { - output.heading('TimeTerm', node.span); - visitUnitTerm(node); - } - - void visitFreqTerm(FreqTerm node) { - output.heading('FreqTerm', node.span); - visitUnitTerm(node); - } - - void visitFractionTerm(FractionTerm node) { - output.heading('FractionTerm', node.span); - output.depth++; - visitLiteralTerm(node); - output.depth--; - } - - void visitUriTerm(UriTerm node) { - output.heading('UriTerm', node.span); - output.depth++; - visitLiteralTerm(node); - output.depth--; - } - - void visitFunctionTerm(FunctionTerm node) { - output.heading('FunctionTerm', node.span); - output.depth++; - visitLiteralTerm(node); - visitExpressions(node._params); - output.depth--; - } - - void visitGroupTerm(GroupTerm node) { - output.heading('GroupTerm', node.span); - output.depth++; - output.writeNodeList('grouped terms', node._terms); - output.depth--; - } - - void visitItemTerm(ItemTerm node) { - output.heading('ItemTerm', node.span); - visitNumberTerm(node); - } - - void visitOperatorSlash(OperatorSlash node) { - output.heading('OperatorSlash', node.span); - } - - void visitOperatorComma(OperatorComma node) { - output.heading('OperatorComma', node.span); - } - - void visitExpressions(Expressions node) { - output.heading('Expressions', node.span); - output.depth++; - output.writeNodeList('expressions', node._expressions); - output.depth--; - } - - void visitBinaryExpression(BinaryExpression node) { - output.heading('BinaryExpression', node.span); - // TODO(terry): TBD - } - - void visitUnaryExpression(UnaryExpression node) { - output.heading('UnaryExpression', node.span); - // TODO(terry): TBD - } - - void visitIdentifier(Identifier node) { - output.heading('Identifier(${output.toValue(node.name)})', node.span); - } - - void visitWildcard(Wildcard node) { - output.heading('Wildcard(*)', node.span); - } - - // TODO(terry): Defined for frog/tree.dart. - void visitTypeReference(TypeReference node) { - output.heading('Unimplemented'); - } -} diff --git a/utils/css/treebase.dart b/utils/css/treebase.dart deleted file mode 100644 index 7bdc3e6b3866..000000000000 --- a/utils/css/treebase.dart +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. -/** - * The base type for all nodes in a dart abstract syntax tree. - */ -class ASTNode { - /** The source code this [ASTNode] represents. */ - SourceSpan span; - - ASTNode(this.span) {} - - /** Classic double-dispatch visitor for implementing passes. */ - abstract visit(TreeVisitor visitor); - - /** A multiline string showing the node and its children. */ - String toDebugString() { - var to = new TreeOutput(); - var tp = new TreePrinter(to); - this.visit(tp); - return to.buf.toString(); - } -} - -/** The base type for expressions. */ -// TODO(terry): Should be abstract class; but frog doesn't support abstract. -class Expression extends ASTNode { - Expression(SourceSpan span): super(span); - - visit(TreeVisitor visitor) {} // TODO(terry): remove when abstract. -} - -/** The base type for a reference to a [Type]. */ -// TODO(terry): Should be abstract class; but frog doesn't support abstract. -class TypeReference extends ASTNode { - TypeReference(SourceSpan span): super(span); - - visit(TreeVisitor visitor) {} // TODO(terry): remove when abstract. -} - -// TODO(jimhug): Clean-up and factor out of core. -/** Simple class to provide a textual dump of trees for debugging. */ -class TreeOutput { - int depth; - StringBuffer buf; - - var printer; - - static void dump(ASTNode node) { - var o = new TreeOutput(); - node.visit(new TreePrinter(o)); - print(o.buf); - } - - TreeOutput(): this.depth = 0, this.buf = new StringBuffer() { - } - - void write(String s) { - for (int i=0; i < depth; i++) { - buf.write(' '); - } - buf.write(s); - } - - void writeln(String s) { - write(s); - buf.write('\n'); - } - - void heading(String name, span) { - write(name); - buf.write(' (${span.locationText})'); - buf.write('\n'); - } - - String toValue(value) { - if (value == null) return 'null'; - else if (value is Identifier) return value.name; - else return value.toString(); - } - - void writeNode(String label, ASTNode node) { - write(label + ': '); - depth += 1; - if (node != null) node.visit(printer); - else writeln('null'); - depth -= 1; - } - - void writeValue(String label, value) { - var v = toValue(value); - writeln('${label}: ${v}'); - } - - void writeList(String label, List list) { - write(label + ': '); - if (list == null) { - buf.write('null'); - buf.write('\n'); - } else { - for (var item in list) { - buf.write(item.toString()); - buf.write(', '); - } - buf.write('\n'); - } - } - - void writeNodeList(String label, List list) { - writeln('${label} ['); - if (list != null) { - depth += 1; - for (var node in list) { - if (node != null) { - node.visit(printer); - } else { - writeln('null'); - } - } - depth -= 1; - writeln(']'); - } - } -} diff --git a/utils/css/uitest.dart b/utils/css/uitest.dart deleted file mode 100644 index bbbbad0a1508..000000000000 --- a/utils/css/uitest.dart +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:html'; -import 'css.dart'; -import '../lib/file_system_memory.dart'; - -void runCss([bool debug = false, bool parseOnly = false]) { - final Document doc = window.document; - final TextAreaElement classes = doc.query("#classes"); - final TextAreaElement expression = doc.query('#expression'); - final TableCellElement validity = doc.query('#validity'); - final TableCellElement result = doc.query('#result'); - - List knownWorld = classes.value.split("\n"); - List knownClasses = []; - List knownIds = []; - for (final name in knownWorld) { - if (name.startsWith('.')) { - knownClasses.add(name.substring(1)); - } else if (name.startsWith('#')) { - knownIds.add(name.substring(1)); - } - } - - CssWorld cssWorld = new CssWorld(knownClasses, knownIds); - bool templateValid = true; - String dumpTree = ""; - - String cssExpr = expression.value; - if (!debug) { - try { - cssParseAndValidate(cssExpr, cssWorld); - } catch (cssException) { - templateValid = false; - dumpTree = cssException.toString(); - } - } else if (parseOnly) { - try { - Parser parser = new Parser(new SourceFile( - SourceFile.IN_MEMORY_FILE, cssExpr)); - Stylesheet stylesheet = parser.parse(); - StringBuffer stylesheetTree = new StringBuffer(); - String prettyStylesheet = stylesheet.toString(); - stylesheetTree.write("${prettyStylesheet}\n"); - stylesheetTree.write("\n============>Tree Dump<============\n"); - stylesheetTree.write(stylesheet.toDebugString()); - dumpTree = stylesheetTree.toString(); - } catch (cssParseException) { - templateValid = false; - dumpTree = cssParseException.toString(); - } - } else { - try { - dumpTree = cssParseAndValidateDebug(cssExpr, cssWorld); - } catch (cssException) { - templateValid = false; - dumpTree = cssException.toString(); - } - } - - final bgcolor = templateValid ? "white" : "red"; - final color = templateValid ? "black" : "white"; - final valid = templateValid ? "VALID" : "NOT VALID"; - String resultStyle = "resize:none; margin:0; height:100%; width:100%;" - "padding:5px 7px;"; - String validityStyle = "font-weight:bold; background-color:$bgcolor;" - "color:$color; border:1px solid black; border-bottom:0px solid white;"; - validity.innerHTML = ''' -
- Expression: $cssExpr is $valid -
- '''; - result.innerHTML = ""; -} - -void main() { - final element = new Element.tag('div'); - element.innerHTML = ''' - - - - - - - -
- - - - - - - - - -
- Classes -
- -
-
- - - - - - - - - - - - - - -
- - - - - - - - - -
- Selector Expression -
- -
-
- - - - - - - - -
- - - - - -
-
- - - - - - - - - - - - -
- Result -
-
- -
-
-
- '''; - - document.body.style.setProperty("background-color", "lightgray"); - document.body.elements.add(element); - - ButtonElement parseButton = window.document.query('#parse'); - parseButton.on.click.add((MouseEvent e) { - runCss(true, true); - }); - - ButtonElement checkButton = window.document.query('#check'); - checkButton.on.click.add((MouseEvent e) { - runCss(); - }); - - ButtonElement debugButton = window.document.query('#debug'); - debugButton.on.click.add((MouseEvent e) { - runCss(true); - }); - - initCssWorld(false); -} diff --git a/utils/css/validate.dart b/utils/css/validate.dart deleted file mode 100644 index 9babe3d3c091..000000000000 --- a/utils/css/validate.dart +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -class Validate { - static int _classNameCheck(var selector, int matches) { - if (selector.isCombinatorDescendant() || - (selector.isCombinatorNone() && matches == 0)) { - if (matches < 0) { - String tooMany = selector.simpleSelector.toString(); - throw new CssSelectorException( - 'Can not mix Id selector with class selector(s). Id ' + - 'selector must be singleton too many starting at $tooMany'); - } - - return matches + 1; - } else { - String error = selector.toString(); - throw new CssSelectorException( - 'Selectors can not have combinators (>, +, or ~) before $error'); - } - } - - static int _elementIdCheck(var selector, int matches) { - if (selector.isCombinatorNone() && matches == 0) { - // Perfect just one element id returns matches of -1. - return -1; - } else if (selector.isCombinatorDescendant()) { - String tooMany = selector.simpleSelector.toString(); - throw new CssSelectorException( - 'Use of Id selector must be singleton starting at $tooMany'); - } else { - String error = selector.simpleSelector.toString(); - throw new CssSelectorException( - 'Selectors can not have combinators (>, +, or ~) before $error'); - } - } - - // Validate the @{css expression} only .class and #elementId are valid inside - // of @{...}. - static template(List selectors, CssWorld cssWorld) { - var errorSelector; // signal which selector didn't match. - bool found = false; // signal if a selector is matched. - int matches = 0; // < 0 IdSelectors, > 0 ClassSelector - - // At most one selector group (any number of simple selector sequences). - assert(selectors.length <= 1); - - for (final sels in selectors) { - for (final selector in sels.simpleSelectorSequences) { - found = false; - var simpleSelector = selector.simpleSelector; - if (simpleSelector is ClassSelector) { - // Any class name starting with an underscore is a private class name - // that doesn't have to match the world of known classes. - if (!simpleSelector.name.startsWith('_')) { - // TODO(terry): For now iterate through all classes look for faster - // mechanism hash map, etc. - for (final className in cssWorld.classes) { - if (selector.simpleSelector.name == className) { - matches = _classNameCheck(selector, matches); - found = true; // .class found. - break; - } - for (final className2 in cssWorld.classes) { - print(className2); - } - } - - } else { - // Don't check any class name that is prefixed with an underscore. - // However, signal as found and bump up matches; it's a valid class - // name. - matches = _classNameCheck(selector, matches); - found = true; // ._class are always okay. - } - } else if (simpleSelector is IdSelector) { - // Any element id starting with an underscore is a private element id - // that doesn't have to match the world of known elemtn ids. - if (!simpleSelector.name.startsWith('_')) { - for (final id in cssWorld.ids) { - if (simpleSelector.name == id) { - matches = _elementIdCheck(selector, matches); - found = true; // #id found. - break; - } - } - } else { - // Don't check any element ID that is prefixed with an underscore. - // Signal as found and bump up matches; it's a valid element ID. - matches = _elementIdCheck(selector, matches); - found = true; // #_id are always okay - } - } else { - String badSelector = simpleSelector.toString(); - throw new CssSelectorException( - 'Invalid template selector $badSelector'); - } - - if (!found) { - String unknownName = simpleSelector.toString(); - throw new CssSelectorException('Unknown selector name $unknownName'); - } - } - } - - // Every selector must match. - var selector = selectors[0]; - assert((matches >= 0 ? matches : -matches) == - selector.simpleSelectorSequences.length); - } -} - diff --git a/utils/css/world.dart b/utils/css/world.dart deleted file mode 100644 index 837eefdfcd3c..000000000000 --- a/utils/css/world.dart +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -/** The one true [World]. */ -World world; - -typedef void MessageHandler(String prefix, String message, SourceSpan span); -typedef void PrintHandler(String message); - -/** - * Should be called exactly once to setup singleton world. - * Can use world.reset() to reinitialize. - */ -void initializeWorld(var files) { - assert(world == null); - world = new World(files); - world.init(); -} - -/** Can be thrown on any compiler error and includes source location. */ -class CompilerException implements Exception { - final String _message; - final SourceSpan _location; - - CompilerException(this._message, this._location); - - String toString() { - if (_location != null) { - return 'CompilerException: ${_location.toMessageString(_message)}'; - } else { - return 'CompilerException: $_message'; - } - } -} - -/** Represents a Dart template "world". */ -class World { - String template; - - var files; - - int errors = 0, warnings = 0; - bool seenFatal = false; - MessageHandler messageHandler; - PrintHandler printHandler; - - World(this.files); - - void reset() { - errors = warnings = 0; - seenFatal = false; - init(); - } - - init() { - } - - - // ********************** Message support *********************** - - void _message(String color, String prefix, String message, - SourceSpan span, SourceSpan span1, SourceSpan span2, bool throwing) { - if (messageHandler != null) { - // TODO(jimhug): Multiple spans cleaner... - messageHandler(prefix, message, span); - if (span1 != null) { - messageHandler(prefix, message, span1); - } - if (span2 != null) { - messageHandler(prefix, message, span2); - } - } else { - final messageWithPrefix = options.useColors - ? (color + prefix + _NO_COLOR + message) : (prefix + message); - - var text = messageWithPrefix; - if (span != null) { - text = span.toMessageString(messageWithPrefix); - } - - String span1Text = span1 != null ? - span1.toMessageString(messageWithPrefix) : ""; - String span2Text = span2 != null ? - span2.toMessageString(messageWithPrefix) : ""; - - if (printHandler == null) { - print(text); - if (span1 != null) { - print(span1Text); - } - if (span2 != null) { - print(span2Text); - } - } else { - printHandler("${text}\r${span1Text}\r${span2Text}"); - } - } - - if (throwing) { - throw new CompilerException(prefix + message, span); - } - } - - /** [message] is considered a static compile-time error by the Dart lang. */ - void error(String message, - [SourceSpan span, SourceSpan span1, SourceSpan span2]) { - errors++; - _message(_RED_COLOR, 'error: ', message, - span, span1, span2, options.throwOnErrors); - } - - /** [message] is considered a type warning by the Dart lang. */ - void warning(String message, - [SourceSpan span, SourceSpan span1, SourceSpan span2]) { - if (options.warningsAsErrors) { - error(message, span, span1, span2); - return; - } - warnings++; - if (options.showWarnings) { - _message(_MAGENTA_COLOR, 'warning: ', message, - span, span1, span2, options.throwOnWarnings); - } - } - - /** [message] at [location] is so bad we can't generate runnable code. */ - void fatal(String message, - [SourceSpan span, SourceSpan span1, SourceSpan span2]) { - errors++; - seenFatal = true; - _message(_RED_COLOR, 'fatal: ', message, - span, span1, span2, options.throwOnFatal || options.throwOnErrors); - } - - /** [message] at [location] is about a bug in the compiler. */ - void internalError(String message, - {SourceSpan span, SourceSpan span1, SourceSpan span2}) { - _message(_NO_COLOR, - 'We are sorry, but...', message, span, span1, span2, true); - } - - /** - * [message] at [location] will tell the user about what the compiler - * is doing. - */ - void info(String message, - [SourceSpan span, SourceSpan span1, SourceSpan span2]) { - if (options.showInfo) { - _message(_GREEN_COLOR, 'info: ', message, span, span1, span2, false); - } - } - - bool get hasErrors => errors > 0; - - withTiming(String name, f()) { - final sw = new Stopwatch(); - sw.start(); - var result = f(); - sw.stop(); - info('$name in ${sw.elapsedMilliseconds}msec'); - return result; - } -} - -// Color constants used for generating messages. -String _GREEN_COLOR = '\u001b[32m'; -String _RED_COLOR = '\u001b[31m'; -String _MAGENTA_COLOR = '\u001b[35m'; -String _NO_COLOR = '\u001b[0m'; diff --git a/utils/lib/file_system.dart b/utils/lib/file_system.dart deleted file mode 100644 index 306be7a785ce..000000000000 --- a/utils/lib/file_system.dart +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -// TODO(terry): Investigate common library for file I/O shared between frog and tools. - -/** Abstraction for file systems and utility functions to manipulate paths. */ -library file_system; - -/** - * Abstraction around file system access to work in a variety of different - * environments. - */ -abstract class FileSystem { - String readAll(String filename); - - void writeString(String outfile, String text); - - bool fileExists(String filename); - - void createDirectory(String path, [bool recursive]); - void removeDirectory(String path, [bool recursive]); -} - -/** - * Replaces all back slashes (\) with forward slashes (/) in [path] and - * return the result. - */ -String canonicalizePath(String path) { - return path.replaceAll('\\', '/'); -} - -/** Join [path1] to [path2]. */ -String joinPaths(String path1, String path2) { - path1 = canonicalizePath(path1); - path2 = canonicalizePath(path2); - - var pieces = path1.split('/'); - for (var piece in path2.split('/')) { - if (piece == '..' && pieces.length > 0 && pieces.last != '.' - && pieces.last != '..') { - pieces.removeLast(); - } else if (piece != '') { - if (pieces.length > 0 && pieces.last == '.') { - pieces.removeLast(); - } - pieces.add(piece); - } - } - return pieces.join('/'); -} - -/** Returns the directory name for the [path]. */ -String dirname(String path) { - path = canonicalizePath(path); - - int lastSlash = path.lastIndexOf('/', path.length); - if (lastSlash == -1) { - return '.'; - } else { - return path.substring(0, lastSlash); - } -} - -/** Returns the file name without directory for the [path]. */ -String basename(String path) { - path = canonicalizePath(path); - - int lastSlash = path.lastIndexOf('/', path.length); - if (lastSlash == -1) { - return path; - } else { - return path.substring(lastSlash + 1); - } -} diff --git a/utils/lib/file_system_memory.dart b/utils/lib/file_system_memory.dart deleted file mode 100644 index c1a15b930b9d..000000000000 --- a/utils/lib/file_system_memory.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -// TODO(terry): Investigate common library for file I/O shared between frog and tools. - -library file_system_memory; - -import 'file_system.dart'; - -/** - * [FileSystem] implementation a memory buffer. - */ -class MemoryFileSystem implements FileSystem { - StringBuffer buffer; - - MemoryFileSystem() : this.buffer = new StringBuffer(); - - void writeString(String outfile, String text) { - buffer.write(text); - } - - String readAll(String filename) { - return buffer.toString(); - } - - bool fileExists(String filename) { - return true; - } - - void createDirectory(String path, [bool recursive]) { - // TODO(terry): To be implement. - throw 'createDirectory() is not implemented by MemoryFileSystem yet.'; - } - - void removeDirectory(String path, [bool recursive]) { - // TODO(terry): To be implement. - throw 'removeDirectory() is not implemented by MemoryFileSystem yet.'; - } -} diff --git a/utils/lib/file_system_vm.dart b/utils/lib/file_system_vm.dart deleted file mode 100644 index 99b936f18afc..000000000000 --- a/utils/lib/file_system_vm.dart +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -// TODO(terry): Investigate common library for file I/O shared between frog and tools. - -library file_system_vm; -import 'dart:convert'; -import 'dart:io'; -import 'file_system.dart'; - -/** File system implementation using the vm api's. */ -class VMFileSystem implements FileSystem { - void writeString(String path, String text) { - var file = new File(path).openSync(mode: FileMode.WRITE); - file.writeStringSync(text); - file.closeSync(); - } - - String readAll(String filename) { - var file = (new File(filename)).openSync(); - var length = file.lengthSync(); - var buffer = new List(length); - var bytes = file.readIntoSync(buffer, 0, length); - file.closeSync(); - return UTF8.decode(bytes); - } - - bool fileExists(String filename) { - return new File(filename).existsSync(); - } - - void createDirectory(String path, [bool recursive = false]) { - // TODO(rnystrom): Implement. - throw 'createDirectory() is not implemented by VMFileSystem yet.'; - } - - void removeDirectory(String path, [bool recursive = false]) { - // TODO(rnystrom): Implement. - throw 'removeDirectory() is not implemented by VMFileSystem yet.'; - } -} diff --git a/utils/template/codegen.dart b/utils/template/codegen.dart deleted file mode 100644 index d2b07ab7ff25..000000000000 --- a/utils/template/codegen.dart +++ /dev/null @@ -1,1013 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -class CGBlock { - int _blockType; // Code type of this block - int _indent; // Number of spaces to prefix for each statement - bool _inEach; // This block or any currently active blocks is a - // #each. If so then any element marked with a - // var attribute is repeated therefore the var - // is a List type instead of an Element type. - String _localName; // optional local name for #each or #with - List _stmts; - int localIndex; // Local variable index (e.g., e0, e1, etc.) - - // Block Types: - static const int CONSTRUCTOR = 0; - static const int EACH = 1; - static const int WITH = 2; - - CGBlock([this._indent = 4, - this._blockType = CGBlock.CONSTRUCTOR, - this._inEach = false, - this._localName = null]) : - _stmts = new List(), localIndex = 0 { - assert(_blockType >= CGBlock.CONSTRUCTOR && _blockType <= CGBlock.WITH); - } - - bool get anyStatements => !_stmts.isEmpty; - bool get isConstructor => _blockType == CGBlock.CONSTRUCTOR; - bool get isEach => _blockType == CGBlock.EACH; - bool get isWith => _blockType == CGBlock.WITH; - - bool get hasLocalName => _localName != null; - String get localName => _localName; - - CGStatement push(var elem, var parentName, [bool exact = false]) { - var varName; - if (elem is TemplateElement && elem.hasVar) { - varName = elem.varName; - } else { - varName = localIndex++; - } - - CGStatement stmt = new CGStatement(elem, _indent, parentName, varName, - exact, _inEach); - _stmts.add(stmt); - - return stmt; - } - - void pop() { - _stmts.removeLast(); - } - - void add(String value) { - if (_stmts.last != null) { - _stmts.last.add(value); - } - } - - CGStatement get last => _stmts.length > 0 ? _stmts.last : null; - - /** - * Returns mixed list of elements marked with the var attribute. If the - * element is inside of a #each the name exposed is: - * - * List varName; - * - * otherwise it's: - * - * var varName; - * - * TODO(terry): For scalars var varName should be Element tag type e.g., - * - * DivElement varName; - */ - String get globalDeclarations { - StringBuffer buff = new StringBuffer(); - for (final CGStatement stmt in _stmts) { - buff.write(stmt.globalDeclaration()); - } - - return buff.toString(); - } - - /** - * List of statement constructors for each var inside a #each. - * - * ${#each products} - *
...
- * ${/each} - * - * returns: - * - * myVar = []; - */ - String get globalInitializers { - StringBuffer buff = new StringBuffer(); - for (final CGStatement stmt in _stmts) { - buff.write(stmt.globalInitializers()); - } - - return buff.toString(); - } - - String get codeBody { - StringBuffer buff = new StringBuffer(); - - for (final CGStatement stmt in _stmts) { - buff.write(stmt.emitDartStatement()); - } - - return buff.toString(); - } -} - -class CGStatement { - bool _exact; // If True not HTML construct instead exact stmt - bool _repeating; // Stmt in a #each this block or nested block. - StringBuffer _buff; - var _elem; - int _indent; - var parentName; - String varName; - bool _globalVariable; - bool _closed; - - CGStatement(this._elem, this._indent, this.parentName, var varNameOrIndex, - [this._exact = false, this._repeating = false]) : - _buff = new StringBuffer(), _closed = false { - - if (varNameOrIndex is String) { - // We have the global variable name - varName = varNameOrIndex; - _globalVariable = true; - } else { - // local index generate local variable name. - varName = "e${varNameOrIndex}"; - _globalVariable = false; - } - } - - bool get hasGlobalVariable => _globalVariable; - String get variableName => varName; - - String globalDeclaration() { - if (hasGlobalVariable) { - String spaces = Codegen.spaces(_indent); - return (_repeating) ? - " List ${varName}; // Repeated elements.\n" : " var ${varName};\n"; - } - - return ""; - } - - String globalInitializers() { - if (hasGlobalVariable && _repeating) { - return " ${varName} = [];\n"; - } - - return ""; - } - - void add(String value) { - _buff.write(value); - } - - bool get isClosed => _closed; - - void close() { - if (_elem is TemplateElement && _elem.scoped) { - add(""); - } - _closed = true; - } - - String emitDartStatement() { - StringBuffer statement = new StringBuffer(); - - String spaces = Codegen.spaces(_indent); - - if (_exact) { - statement.add("${spaces}${_buff.toString()};\n"); - } else { - String localVar = ""; - String tmpRepeat; - if (hasGlobalVariable) { - if (_repeating) { - tmpRepeat = "tmp_${varName}"; - localVar = "var "; - } - } else { - localVar = "var "; - } - - /* Emiting the following code fragment where varName is the attribute - value for var= - - varName = new Element.html('HTML GOES HERE'); - parent.elements.add(varName); - - for repeating elements in a #each: - - var tmp_nnn = new Element.html('HTML GOES HERE'); - varName.add(tmp_nnn); - parent.elements.add(tmp_nnn); - - for elements w/o var attribute set: - - var eNNN = new Element.html('HTML GOES HERE'); - parent.elements.add(eNNN); - */ - if (_elem is TemplateCall) { - // Call template NameEntry2 - String cls = _elem.toCall; - String params = _elem.params; - statement.add("\n${spaces}// Call template ${cls}.\n"); - statement.add( - "${spaces}${localVar}${varName} = new ${cls}${params};\n"); - statement.add( - "${spaces}${parentName}.elements.add(${varName}.root);\n"); - } else { - bool isTextNode = _elem is TemplateText; - String createType = isTextNode ? "Text" : "Element.html"; - if (tmpRepeat == null) { - statement.add("${spaces}${localVar}${varName} = new ${createType}('"); - } else { - statement.add( - "${spaces}${localVar}${tmpRepeat} = new ${createType}('"); - } - statement.add(isTextNode ? _buff.toString().trim() : _buff.toString()); - - if (tmpRepeat == null) { - statement.add( - "');\n${spaces}${parentName}.elements.add(${varName});\n"); - } else { - statement.add( - "');\n${spaces}${parentName}.elements.add(${tmpRepeat});\n"); - statement.add("${spaces}${varName}.add(${tmpRepeat});\n"); - } - } - } - - return statement.toString(); - } -} - -class Codegen { - static const String SPACES = " "; - static String spaces(int numSpaces) { - return SPACES.substring(0, numSpaces); - } - - // TODO(terry): Before generating Dart class need a validate phase that - // checks mangles all class names to be prefix with the - // template name to avoid any class name collisions. Also, - // investigate possible runtime check mode to insure that only - // valid CSS class names are used (in case someone uses strings - // and not the generated getters to the CSS class selector. This - // mode would be slower would require that every class name set - // (maybe jQuery too) is for a particular view (requires walking - // the HTML tree looking for a parent template prefix that - // matches the CSS prefix. (more thinking needed). - static String generate(List