Migrated Jael

This commit is contained in:
thomashii@dukefirehawk.com 2021-04-29 15:21:31 +08:00
parent 436f797982
commit ea6d566607
32 changed files with 352 additions and 312 deletions

View file

@ -1,12 +1,12 @@
# 4.0.0 (NNBD) # 4.0.0 (NNBD)
* Changed Dart SDK requirements for all packages to ">=2.12.0 <3.0.0" to support NNBD. * Changed Dart SDK requirements for all packages to ">=2.12.0 <3.0.0" to support NNBD.
* Migrated pretty_logging to 3.0.0 (0/0 tests) * Migrated pretty_logging to 3.0.0 (0/0 tests passed)
* Migrated angel_http_exception to 3.0.0 (0/0 tests) * Migrated angel_http_exception to 3.0.0 (0/0 tests passed)
* Moved angel_cli to https://github.com/dukefirehawk/cli (Not migrated) * Moved angel_cli to https://github.com/dukefirehawk/cli (Not migrated)
* Added code_buffer and migrated to 2.0.0 (16/16 tests) * Added code_buffer and migrated to 2.0.0 (16/16 tests passed)
* Added combinator and migrated to 2.0.0 (16/16 tests) * Added combinator and migrated to 2.0.0 (16/16 tests passed)
* Migrated angel_route to 5.0.0 (35/35 tests passed) * Migrated angel_route to 5.0.0 (35/35 tests passed)
* Migrated angel_model to 3.0.0 (0/0 tests) * Migrated angel_model to 3.0.0 (0/0 tests passed)
* Migrated angel_container to 3.0.0 (55/55 tests passed) * Migrated angel_container to 3.0.0 (55/55 tests passed)
* Added merge_map and migrated to 2.0.0 (6/6 tests passed) * Added merge_map and migrated to 2.0.0 (6/6 tests passed)
* Added mock_request and migrated to 2.0.0 (0/0 tests) * Added mock_request and migrated to 2.0.0 (0/0 tests)
@ -19,7 +19,7 @@
* Migrated angel_websocket to 4.0.0 (2/3 tests passed) * Migrated angel_websocket to 4.0.0 (2/3 tests passed)
* Updated test to 4.0.0 (1/1 test passed) * Updated test to 4.0.0 (1/1 test passed)
* Added symbol_table and migrated to 2.0.0 (16/16 tests passed) * Added symbol_table and migrated to 2.0.0 (16/16 tests passed)
* Updated jael to 3.0.0 (in progress) * Migrated jael to 4.0.0 (17/20 tests passed)
* Updated jael_preprocessor to 3.0.0 (in progress) * Updated jael_preprocessor to 3.0.0 (in progress)
* Updated angel_jael to 3.0.0 (in progress) * Updated angel_jael to 3.0.0 (in progress)
* Updated pub_sub to 3.0.0 (in progress) * Updated pub_sub to 3.0.0 (in progress)
@ -30,27 +30,27 @@
# 3.0.0 (Non NNBD) # 3.0.0 (Non NNBD)
* Changed Dart SDK requirements for all packages to ">=2.10.0 <3.0.0" * Changed Dart SDK requirements for all packages to ">=2.10.0 <3.0.0"
* Updated pretty_logging to 2.0.0 * Updated pretty_logging to 2.0.0 (0/0 tests passed)
* Updated angel_http_exception to 2.0.0 * Updated angel_http_exception to 2.0.0 (0/0 tests passed)
* Updated angel_cli to 3.0.0. (Rename not working) * Updated angel_cli to 3.0.0. (Rename not working)
* Updated angel_route to 4.0.0 * Updated angel_route to 4.0.0 (35/35 tests passed)
* Updated angel_model to 2.0.0 * Updated angel_model to 2.0.0 (0/0 tests passed)
* Updated angel_container to 2.0.0 * Updated angel_container to 2.0.0 (55/55 tests passed)
* Updated angel_framework to 3.0.0 * Updated angel_framework to 3.0.0 (151/151 tests passed)
* Updated angel_auth to 3.0.0 * Updated angel_auth to 3.0.0 (28/32 tests passed)
* Updated angel_configuration to 3.0.0 * Updated angel_configuration to 3.0.0 (6/8 tests passed)
* Updated angel_validate to 3.0.0 * Updated angel_validate to 3.0.0 (7/7 tests passed)
* Added and updated json_god to 3.0.0 * Added and updated json_god to 3.0.0 (7/7 tests passed)
* Updated angel_client to 3.0.0 * Updated angel_client to 3.0.0 (10/13 tests passed)
* Updated angel_websocket to 3.0.0 * Updated angel_websocket to 3.0.0 (3/3 tests passed)
* Updated jael to 3.0.0 * Updated jael to 3.0.0 (20/20 tests passed)
* Updated jael_preprocessor to 3.0.0 * Updated jael_preprocessor to 3.0.0 (5/5 tests passed)
* Updated test to 3.0.0 * Updated test to 3.0.0 (1/1 tests passed)
* Updated angel_jael to 3.0.0 (Issue with 2 dependencies) * Updated angel_jael to 3.0.0 (1/1 tests passed, Issue with 2 dependencies)
* Added pub_sub and updated to 3.0.0 * Added pub_sub and updated to 3.0.0 (8/16 tests passed)
* Updated production to 2.0.0 * Updated production to 2.0.0 (0/0 tests passed)
* Updated hot to 3.0.0 * Updated hot to 3.0.0 (0/0 tests passed)
* Updated static to 3.0.0 * Updated static to 3.0.0 (12/12 tests passed)
* Update basic-sdk-2.12.x boilerplate * Update basic-sdk-2.12.x boilerplate
* Updated angel_serialize to 3.0.0 * Updated angel_serialize to 3.0.0
* Updated angel_serialize_generator to 3.0.0 * Updated angel_serialize_generator to 3.0.0

View file

@ -85,7 +85,6 @@ Future<void> formatStat(
break; break;
default: default:
throw 'No file or directory found at "$path".'; throw 'No file or directory found at "$path".';
break;
} }
} }
@ -120,5 +119,9 @@ String? format(String? filename, String content, ArgResults argResults) {
int.parse(argResults['tab-size'] as String), int.parse(argResults['tab-size'] as String),
argResults['insert-spaces'] as bool?, argResults['insert-spaces'] as bool?,
int.parse(argResults['line-length'] as String)); int.parse(argResults['line-length'] as String));
if (doc == null) {
return null;
}
return fmt.apply(doc); return fmt.apply(doc);
} }

View file

@ -3,7 +3,7 @@ import 'expression.dart';
import 'token.dart'; import 'token.dart';
class Array extends Expression { class Array extends Expression {
final Token? lBracket, rBracket; final Token lBracket, rBracket;
final List<Expression> items; final List<Expression> items;
Array(this.lBracket, this.rBracket, this.items); Array(this.lBracket, this.rBracket, this.items);
@ -14,28 +14,28 @@ class Array extends Expression {
@override @override
FileSpan get span { FileSpan get span {
return items return items
.fold<FileSpan?>(lBracket!.span, (out, i) => out!.expand(i.span!))! .fold<FileSpan?>(lBracket.span, (out, i) => out!.expand(i.span))!
.expand(rBracket!.span!); .expand(rBracket.span);
} }
} }
class IndexerExpression extends Expression { class IndexerExpression extends Expression {
final Expression? target, indexer; final Expression target, indexer;
final Token? lBracket, rBracket; final Token lBracket, rBracket;
IndexerExpression(this.target, this.lBracket, this.indexer, this.rBracket); IndexerExpression(this.target, this.lBracket, this.indexer, this.rBracket);
@override @override
FileSpan get span { FileSpan get span {
return target!.span! return target.span
.expand(lBracket!.span!) .expand(lBracket.span)
.expand(indexer!.span!) .expand(indexer.span)
.expand(rBracket!.span!); .expand(rBracket.span);
} }
@override @override
dynamic compute(scope) { dynamic compute(scope) {
var a = target!.compute(scope), b = indexer!.compute(scope); var a = target.compute(scope), b = indexer.compute(scope);
return a[b]; return a[b];
} }
} }

View file

@ -1,5 +1,5 @@
import 'package:source_span/source_span.dart'; import 'package:source_span/source_span.dart';
abstract class AstNode { abstract class AstNode {
FileSpan? get span; FileSpan get span;
} }

View file

@ -15,13 +15,14 @@ class Attribute extends AstNode {
bool get isRaw => nequ != null; bool get isRaw => nequ != null;
Expression? get nameNode => id ?? string; Expression get nameNode => id ?? string!;
String get name => string?.value ?? id!.name; String get name => string?.value ?? id!.name;
@override @override
FileSpan? get span { FileSpan get span {
if (equals == null) return nameNode!.span; if (equals == null || value == null) return nameNode.span;
return nameNode!.span!.expand(equals?.span ?? nequ!.span!).expand(value!.span!); //return nameNode.span.expand(equals!.span ?? nequ!.span).expand(value!.span);
return nameNode.span.expand(equals!.span).expand(value!.span);
} }
} }

View file

@ -3,16 +3,16 @@ import 'expression.dart';
import 'token.dart'; import 'token.dart';
class BinaryExpression extends Expression { class BinaryExpression extends Expression {
final Expression? left, right; final Expression left, right;
final Token? operator; final Token operator;
BinaryExpression(this.left, this.operator, this.right); BinaryExpression(this.left, this.operator, this.right);
@override @override
compute(scope) { dynamic compute(scope) {
var l = left!.compute(scope), r = right!.compute(scope); var l = left.compute(scope), r = right.compute(scope);
switch (operator?.type) { switch (operator.type) {
case TokenType.asterisk: case TokenType.asterisk:
return l * r; return l * r;
case TokenType.slash: case TokenType.slash:
@ -38,10 +38,10 @@ class BinaryExpression extends Expression {
return l ?? r; return l ?? r;
default: default:
throw UnsupportedError( throw UnsupportedError(
'Unsupported binary operator: "${operator?.span?.text ?? "<null>"}".'); 'Unsupported binary operator: "${operator.span.text ?? "<null>"}".');
} }
} }
@override @override
FileSpan get span => left!.span!.expand(operator!.span!).expand(right!.span!); FileSpan get span => left.span.expand(operator.span).expand(right.span);
} }

View file

@ -6,8 +6,8 @@ import 'identifier.dart';
import 'token.dart'; import 'token.dart';
class Call extends Expression { class Call extends Expression {
final Expression? target; final Expression target;
final Token? lParen, rParen; final Token lParen, rParen;
final List<Expression> arguments; final List<Expression> arguments;
final List<NamedArgument> namedArguments; final List<NamedArgument> namedArguments;
@ -17,24 +17,24 @@ class Call extends Expression {
@override @override
FileSpan get span { FileSpan get span {
return arguments return arguments
.fold<FileSpan?>(target!.span, (out, a) => out!.expand(a.span!))! .fold<FileSpan?>(target.span, (out, a) => out!.expand(a.span))!
.expand(namedArguments.fold<FileSpan?>( .expand(namedArguments.fold<FileSpan?>(
lParen!.span, (out, a) => out!.expand(a.span))!) lParen.span, (out, a) => out!.expand(a.span))!)
.expand(rParen!.span!); .expand(rParen.span);
} }
List computePositional(SymbolTable scope) => List computePositional(SymbolTable? scope) =>
arguments.map((e) => e.compute(scope)).toList(); arguments.map((e) => e.compute(scope)).toList();
Map<Symbol, dynamic> computeNamed(SymbolTable scope) { Map<Symbol, dynamic> computeNamed(SymbolTable? scope) {
return namedArguments.fold<Map<Symbol, dynamic>>({}, (out, a) { return namedArguments.fold<Map<Symbol, dynamic>>({}, (out, a) {
return out..[Symbol(a.name.name)] = a.value.compute(scope); return out..[Symbol(a.name.name)] = a.value.compute(scope);
}); });
} }
@override @override
compute(scope) { dynamic compute(scope) {
var callee = target!.compute(scope); var callee = target.compute(scope);
var args = computePositional(scope); var args = computePositional(scope);
var named = computeNamed(scope); var named = computeNamed(scope);
@ -44,13 +44,13 @@ class Call extends Expression {
class NamedArgument extends AstNode { class NamedArgument extends AstNode {
final Identifier name; final Identifier name;
final Token? colon; final Token colon;
final Expression value; final Expression value;
NamedArgument(this.name, this.colon, this.value); NamedArgument(this.name, this.colon, this.value);
@override @override
FileSpan get span { FileSpan get span {
return name.span!.expand(colon!.span!).expand(value.span!); return name.span.expand(colon.span).expand(value.span);
} }
} }

View file

@ -3,29 +3,29 @@ import 'expression.dart';
import 'token.dart'; import 'token.dart';
class Conditional extends Expression { class Conditional extends Expression {
final Expression? condition, ifTrue, ifFalse; final Expression condition, ifTrue, ifFalse;
final Token? question, colon; final Token question, colon;
Conditional( Conditional(
this.condition, this.question, this.ifTrue, this.colon, this.ifFalse); this.condition, this.question, this.ifTrue, this.colon, this.ifFalse);
@override @override
FileSpan get span { FileSpan get span {
return condition!.span! return condition.span
.expand(question!.span!) .expand(question.span)
.expand(ifTrue!.span!) .expand(ifTrue.span)
.expand(colon!.span!) .expand(colon.span)
.expand(ifFalse!.span!); .expand(ifFalse.span);
} }
@override @override
compute(scope) { dynamic compute(scope) {
var v = condition!.compute(scope) as bool?; var v = condition.compute(scope) as bool;
if (scope.resolve('!strict!')?.value == false) { if (scope?.resolve('!strict!')?.value == false) {
v = v == true; v = v == true;
} }
return v! ? ifTrue!.compute(scope) : ifFalse!.compute(scope); return v ? ifTrue.compute(scope) : ifFalse.compute(scope);
} }
} }

View file

@ -12,33 +12,34 @@ class Document extends AstNode {
Document(this.doctype, this.root); Document(this.doctype, this.root);
@override @override
FileSpan? get span { FileSpan get span {
if (doctype == null) return root.span; if (doctype == null) return root.span;
return doctype!.span.expand(root.span!); return doctype!.span.expand(root.span);
} }
} }
class HtmlComment extends ElementChild { class HtmlComment extends ElementChild {
final Token? htmlComment; final Token htmlComment;
HtmlComment(this.htmlComment); HtmlComment(this.htmlComment);
@override @override
FileSpan? get span => htmlComment!.span; FileSpan get span => htmlComment.span;
} }
class Text extends ElementChild { class Text extends ElementChild {
final Token? text; final Token text;
Text(this.text); Text(this.text);
@override @override
FileSpan? get span => text!.span; FileSpan get span => text.span;
} }
class Doctype extends AstNode { class Doctype extends AstNode {
final Token? lt, doctype, gt; final Token lt, doctype, gt;
final Identifier? html, public; final Identifier html;
final Identifier? public;
final StringLiteral? name, url; final StringLiteral? name, url;
Doctype(this.lt, this.doctype, this.html, this.public, this.name, this.url, Doctype(this.lt, this.doctype, this.html, this.public, this.name, this.url,
@ -46,15 +47,15 @@ class Doctype extends AstNode {
@override @override
FileSpan get span { FileSpan get span {
if (public == null) { if (public == null || name == null || url == null) {
return lt!.span!.expand(doctype!.span!).expand(html!.span!).expand(gt!.span!); return lt.span.expand(doctype.span).expand(html.span).expand(gt.span);
} }
return lt!.span! return lt.span
.expand(doctype!.span!) .expand(doctype.span)
.expand(html!.span!) .expand(html.span)
.expand(public!.span!) .expand(public!.span)
.expand(name!.span!) .expand(name!.span)
.expand(url!.span!) .expand(url!.span)
.expand(gt!.span!); .expand(gt.span);
} }
} }

View file

@ -13,7 +13,7 @@ class TextNode extends ElementChild {
TextNode(this.text); TextNode(this.text);
@override @override
FileSpan? get span => text.span; FileSpan get span => text.span;
} }
abstract class Element extends ElementChild { abstract class Element extends ElementChild {
@ -44,10 +44,13 @@ abstract class Element extends ElementChild {
} }
class SelfClosingElement extends Element { class SelfClosingElement extends Element {
final Token? lt, slash, gt; final Token? slash;
final Token lt, gt;
@override
final Identifier tagName; final Identifier tagName;
@override
final Iterable<Attribute> attributes; final Iterable<Attribute> attributes;
@override @override
@ -59,20 +62,19 @@ class SelfClosingElement extends Element {
@override @override
FileSpan get span { FileSpan get span {
var start = attributes.fold<FileSpan>( var start = attributes.fold<FileSpan>(
lt!.span!.expand(tagName.span!), (out, a) => out.expand(a.span!)); lt.span.expand(tagName.span), (out, a) => out.expand(a.span));
return slash != null return slash != null
? start.expand(slash!.span!).expand(gt!.span!) ? start.expand(slash!.span).expand(gt.span)
: start.expand(gt!.span!); : start.expand(gt.span);
} }
} }
class RegularElement extends Element { class RegularElement extends Element {
final Token? lt, gt, lt2, slash, gt2; final Token? gt2;
final Token lt2, slash, lt, gt;
final Identifier tagName, tagName2; final Identifier tagName, tagName2;
final Iterable<Attribute> attributes; final Iterable<Attribute> attributes;
final Iterable<ElementChild> children; final Iterable<ElementChild> children;
RegularElement(this.lt, this.tagName, this.attributes, this.gt, this.children, RegularElement(this.lt, this.tagName, this.attributes, this.gt, this.children,
@ -82,16 +84,16 @@ class RegularElement extends Element {
FileSpan get span { FileSpan get span {
var openingTag = attributes var openingTag = attributes
.fold<FileSpan>( .fold<FileSpan>(
lt!.span!.expand(tagName.span!), (out, a) => out.expand(a.span!)) lt.span.expand(tagName.span), (out, a) => out.expand(a.span))
.expand(gt!.span!); .expand(gt.span);
if (gt2 == null) return openingTag; if (gt2 == null) return openingTag;
return children return children
.fold<FileSpan>(openingTag, (out, c) => out.expand(c.span!)) .fold<FileSpan>(openingTag, (out, c) => out.expand(c.span))
.expand(lt2!.span!) .expand(lt2.span)
.expand(slash!.span!) .expand(slash.span)
.expand(tagName2.span!) .expand(tagName2.span)
.expand(gt2!.span!); .expand(gt2!.span);
} }
} }

View file

@ -3,15 +3,15 @@ import 'package:source_span/source_span.dart';
class JaelError extends Error { class JaelError extends Error {
final JaelErrorSeverity severity; final JaelErrorSeverity severity;
final String message; final String message;
final FileSpan? span; final FileSpan span;
JaelError(this.severity, this.message, this.span); JaelError(this.severity, this.message, this.span);
@override @override
String toString() { String toString() {
var label = severity == JaelErrorSeverity.warning ? 'warning' : 'error'; var label = severity == JaelErrorSeverity.warning ? 'warning' : 'error';
return '$label: ${span!.start.toolString}: $message\n' + return '$label: ${span.start.toolString}: $message\n' +
span!.highlight(color: true); span.highlight(color: true);
} }
} }

View file

@ -4,30 +4,29 @@ import 'ast_node.dart';
import 'token.dart'; import 'token.dart';
abstract class Expression extends AstNode { abstract class Expression extends AstNode {
dynamic compute(SymbolTable scope); dynamic compute(SymbolTable? scope);
} }
abstract class Literal extends Expression {} abstract class Literal extends Expression {}
class Negation extends Expression { class Negation extends Expression {
final Token? exclamation; final Token exclamation;
final Expression? expression; final Expression expression;
Negation(this.exclamation, this.expression); Negation(this.exclamation, this.expression);
@override @override
FileSpan get span { FileSpan get span {
return exclamation!.span!.expand(expression!.span!); return exclamation.span.expand(expression.span);
} }
@override @override
compute(SymbolTable scope) { bool compute(SymbolTable? scope) {
var v = expression!.compute(scope) as bool?; var v = expression.compute(scope) as bool;
if (scope?.resolve('!strict!')?.value == false) {
if (scope.resolve('!strict!')?.value == false) {
v = v == true; v = v == true;
} }
return !v!; return !v;
} }
} }

View file

@ -4,12 +4,12 @@ import 'expression.dart';
import 'token.dart'; import 'token.dart';
class Identifier extends Expression { class Identifier extends Expression {
final Token? id; final Token id;
Identifier(this.id); Identifier(this.id);
@override @override
compute(SymbolTable scope) { dynamic compute(SymbolTable? scope) {
switch (name) { switch (name) {
case 'null': case 'null':
return null; return null;
@ -18,30 +18,30 @@ class Identifier extends Expression {
case 'false': case 'false':
return false; return false;
default: default:
var symbol = scope.resolve(name); var symbol = scope?.resolve(name);
if (symbol == null) { if (symbol == null) {
if (scope.resolve('!strict!')?.value == false) return null; if (scope?.resolve('!strict!')?.value == false) return null;
throw ArgumentError('The name "$name" does not exist in this scope.'); throw ArgumentError('The name "$name" does not exist in this scope.');
} }
return scope.resolve(name)!.value; return scope?.resolve(name)!.value;
} }
} }
String get name => id!.span!.text; String get name => id.span.text ?? '';
@override @override
FileSpan? get span => id!.span; FileSpan get span => id.span;
} }
class SyntheticIdentifier extends Identifier { class SyntheticIdentifier extends Identifier {
@override @override
final String name; final String name;
SyntheticIdentifier(this.name, [Token? token]) : super(token); SyntheticIdentifier(this.name, [Token? token]) : super(token!);
@override @override
FileSpan? get span { FileSpan get span {
if (id != null) return id!.span; return id.span;
throw UnsupportedError('Cannot get the span of a SyntheticIdentifier.'); //throw UnsupportedError('Cannot get the span of a SyntheticIdentifier.');
} }
} }

View file

@ -4,15 +4,15 @@ import 'expression.dart';
import 'token.dart'; import 'token.dart';
class Interpolation extends ElementChild { class Interpolation extends ElementChild {
final Token? doubleCurlyL, doubleCurlyR; final Token doubleCurlyL, doubleCurlyR;
final Expression expression; final Expression expression;
Interpolation(this.doubleCurlyL, this.expression, this.doubleCurlyR); Interpolation(this.doubleCurlyL, this.expression, this.doubleCurlyR);
bool get isRaw => doubleCurlyL!.span!.text.endsWith('-'); bool get isRaw => doubleCurlyL.span.text?.endsWith('-') ?? false;
@override @override
FileSpan get span { FileSpan get span {
return doubleCurlyL!.span!.expand(expression.span!).expand(doubleCurlyR!.span!); return doubleCurlyL.span.expand(expression.span).expand(doubleCurlyR.span);
} }
} }

View file

@ -5,26 +5,26 @@ import 'identifier.dart';
import 'token.dart'; import 'token.dart';
class MapLiteral extends Literal { class MapLiteral extends Literal {
final Token? lCurly, rCurly; final Token lCurly, rCurly;
final List<KeyValuePair> pairs; final List<KeyValuePair> pairs;
MapLiteral(this.lCurly, this.pairs, this.rCurly); MapLiteral(this.lCurly, this.pairs, this.rCurly);
@override @override
compute(scope) { Map compute(scope) {
return pairs.fold<Map>({}, (out, p) { return pairs.fold<Map>({}, (out, p) {
var key, value; var key, value;
if (p.colon == null) { if (p.colon == null) {
if (p.key is! Identifier) { if (p.key is! Identifier) {
key = value = p.key!.compute(scope); key = value = p.key.compute(scope);
} else { } else {
key = (p.key as Identifier).name; key = (p.key as Identifier).name;
value = p.key!.compute(scope); value = p.key.compute(scope);
} }
} else { } else {
key = p.key!.compute(scope); key = p.key.compute(scope);
value = p.value!.compute(scope); value = p.value?.compute(scope);
} }
return out..[key] = value; return out..[key] = value;
@ -34,20 +34,22 @@ class MapLiteral extends Literal {
@override @override
FileSpan get span { FileSpan get span {
return pairs return pairs
.fold<FileSpan?>(lCurly!.span, (out, p) => out!.expand(p.span!))! .fold<FileSpan?>(lCurly.span, (out, p) => out?.expand(p.span))!
.expand(rCurly!.span!); .expand(rCurly.span);
} }
} }
class KeyValuePair extends AstNode { class KeyValuePair extends AstNode {
final Expression? key, value; final Expression key;
final Expression? value;
final Token? colon; final Token? colon;
KeyValuePair(this.key, this.colon, this.value); KeyValuePair(this.key, this.colon, this.value);
@override @override
FileSpan? get span { FileSpan get span {
if (colon == null) return key!.span; if (colon == null || value == null) return key.span;
return colon!.span!.expand(colon!.span!).expand(value!.span!); return colon!.span.expand(colon!.span).expand(value!.span);
} }
} }

View file

@ -6,19 +6,19 @@ import 'identifier.dart';
import 'token.dart'; import 'token.dart';
class MemberExpression extends Expression { class MemberExpression extends Expression {
final Expression? expression; final Expression expression;
final Token? op; final Token op;
final Identifier name; final Identifier name;
MemberExpression(this.expression, this.op, this.name); MemberExpression(this.expression, this.op, this.name);
@override @override
compute(SymbolTable scope) { dynamic compute(SymbolTable? scope) {
var target = expression!.compute(scope); var target = expression.compute(scope);
if (op!.span!.text == '?.' && target == null) return null; if (op.span.text == '?.' && target == null) return null;
return reflect(target).getField(Symbol(name.name)).reflectee; return reflect(target).getField(Symbol(name.name)).reflectee;
} }
@override @override
FileSpan get span => expression!.span!.expand(op!.span!).expand(name.span!); FileSpan get span => expression.span.expand(op.span).expand(name.span);
} }

View file

@ -6,17 +6,17 @@ import 'member.dart';
import 'token.dart'; import 'token.dart';
class NewExpression extends Expression { class NewExpression extends Expression {
final Token? $new; final Token $new;
final Call call; final Call call;
NewExpression(this.$new, this.call); NewExpression(this.$new, this.call);
@override @override
FileSpan get span => $new!.span!.expand(call.span); FileSpan get span => $new.span.expand(call.span);
@override @override
compute(scope) { dynamic compute(scope) {
var targetType = call.target!.compute(scope); var targetType = call.target.compute(scope);
var positional = call.computePositional(scope); var positional = call.computePositional(scope);
var named = call.computeNamed(scope); var named = call.computeNamed(scope);
var name = ''; var name = '';

View file

@ -4,13 +4,13 @@ import 'expression.dart';
import 'token.dart'; import 'token.dart';
class NumberLiteral extends Literal { class NumberLiteral extends Literal {
final Token? number; final Token number;
num? _value; num? _value;
NumberLiteral(this.number); NumberLiteral(this.number);
@override @override
FileSpan? get span => number!.span; FileSpan get span => number.span;
static num parse(String value) { static num parse(String value) {
var e = value.indexOf('E'); var e = value.indexOf('E');
@ -24,24 +24,30 @@ class NumberLiteral extends Literal {
} }
@override @override
compute(scope) { num compute(scope) {
return _value ??= parse(number!.span!.text); if (number.span.text == null) {
return 0;
}
return _value ??= parse(number.span.text!);
} }
} }
class HexLiteral extends Literal { class HexLiteral extends Literal {
final Token? hex; final Token hex;
num? _value; num? _value;
HexLiteral(this.hex); HexLiteral(this.hex);
@override @override
FileSpan? get span => hex!.span; FileSpan get span => hex.span;
static num parse(String value) => int.parse(value.substring(2), radix: 16); static num parse(String value) => int.parse(value.substring(2), radix: 16);
@override @override
compute(scope) { num compute(scope) {
return _value ??= parse(hex!.span!.text); if (hex.span.text == null) {
return 0;
}
return _value ??= parse(hex.span.text!);
} }
} }

View file

@ -6,17 +6,21 @@ import 'expression.dart';
import 'token.dart'; import 'token.dart';
class StringLiteral extends Literal { class StringLiteral extends Literal {
final Token? string; final Token string;
final String value; final String value;
StringLiteral(this.string, this.value); StringLiteral(this.string, this.value);
static String parseValue(Token string) { static String parseValue(Token string) {
var text = string.span!.text.substring(1, string.span!.text.length - 1);
var codeUnits = text.codeUnits;
var buf = StringBuffer(); var buf = StringBuffer();
if (string.span.text == null) {
return buf.toString();
}
for (int i = 0; i < codeUnits.length; i++) { var text = string.span.text!.substring(1, string.span.text!.length - 1);
var codeUnits = text.codeUnits;
for (var i = 0; i < codeUnits.length; i++) {
var ch = codeUnits[i]; var ch = codeUnits[i];
if (ch == $backslash) { if (ch == $backslash) {
@ -66,10 +70,10 @@ class StringLiteral extends Literal {
} }
@override @override
compute(SymbolTable scope) { String compute(SymbolTable? scope) {
return value; return value;
} }
@override @override
FileSpan? get span => string!.span; FileSpan get span => string.span;
} }

View file

@ -2,14 +2,14 @@ import 'package:source_span/source_span.dart';
class Token { class Token {
final TokenType type; final TokenType type;
final FileSpan? span; final FileSpan span;
final Match? match; final Match? match;
Token(this.type, this.span, this.match); Token(this.type, this.span, this.match);
@override @override
String toString() { String toString() {
return '${span!.start.toolString}: "${span!.text}" => $type'; return '${span.start.toolString}: "${span.text}" => $type';
} }
} }

View file

@ -5,13 +5,13 @@ class JaelFormatter {
final num tabSize; final num tabSize;
final bool? insertSpaces; final bool? insertSpaces;
final int maxLineLength; final int maxLineLength;
var _buffer = StringBuffer(); final _buffer = StringBuffer();
int _level = 0; int _level = 0;
String? _spaces; String? _spaces;
static String _spaceString(int tabSize) { static String _spaceString(int tabSize) {
var b = StringBuffer(); var b = StringBuffer();
for (int i = 0; i < tabSize; i++) { for (var i = 0; i < tabSize; i++) {
b.write(' '); b.write(' ');
} }
return b.toString(); return b.toString();
@ -30,34 +30,34 @@ class JaelFormatter {
} }
void _applySpacing() { void _applySpacing() {
for (int i = 0; i < _level; i++) { for (var i = 0; i < _level; i++) {
_buffer.write(_spaces); _buffer.write(_spaces);
} }
} }
int get _spaceLength { int get _spaceLength {
var out = 0; var out = 0;
for (int i = 0; i < _level; i++) { for (var i = 0; i < _level; i++) {
out += _spaces!.length; out += _spaces!.length;
} }
return out; return out;
} }
String apply(Document? document) { String apply(Document document) {
if (document?.doctype != null) { if (document.doctype != null) {
_buffer.write('<!doctype'); _buffer.write('<!doctype');
if (document!.doctype!.html != null) _buffer.write(' html'); if (document.doctype?.html != null) _buffer.write(' html');
if (document.doctype!.public != null) _buffer.write(' public'); if (document.doctype?.public != null) _buffer.write(' public');
if (document.doctype!.url != null) { if (document.doctype?.url != null) {
_buffer.write('${document.doctype!.url}'); _buffer.write('${document.doctype!.url}');
} }
_buffer.writeln('>'); _buffer.writeln('>');
} }
_formatChild(document?.root, 0); _formatChild(document.root, 0);
return _buffer.toString().trim(); return _buffer.toString().trim();
} }
@ -72,11 +72,11 @@ class JaelFormatter {
var b = StringBuffer('{{'); var b = StringBuffer('{{');
if (child.isRaw) b.write('-'); if (child.isRaw) b.write('-');
b.write(' '); b.write(' ');
b.write(child.expression.span!.text.trim()); b.write(child.expression.span.text?.trim());
b.write(' }}'); b.write(' }}');
s = b.toString(); s = b.toString();
} else { } else {
s = child.span!.text; s = child.span.text ?? '';
} }
if (isFirst) { if (isFirst) {
s = s.trimLeft(); s = s.trimLeft();
@ -186,7 +186,7 @@ class JaelFormatter {
} else { } else {
if (attr.nequ != null) b.write('!='); if (attr.nequ != null) b.write('!=');
if (attr.equals != null) b.write('='); if (attr.equals != null) b.write('=');
b.write(attr.value!.span!.text); b.write(attr.value!.span.text);
} }
} }
return b.toString(); return b.toString();

View file

@ -1,6 +1,7 @@
import 'dart:convert'; import 'dart:convert';
import 'package:code_buffer/code_buffer.dart'; import 'package:code_buffer/code_buffer.dart';
import 'package:collection/collection.dart' show IterableExtension; import 'package:collection/collection.dart' show IterableExtension;
import 'package:source_span/source_span.dart';
import 'package:symbol_table/symbol_table.dart'; import 'package:symbol_table/symbol_table.dart';
import 'ast/ast.dart'; import 'ast/ast.dart';
import 'text/parser.dart'; import 'text/parser.dart';
@ -8,7 +9,7 @@ import 'text/scanner.dart';
/// Parses a Jael document. /// Parses a Jael document.
Document? parseDocument(String text, Document? parseDocument(String text,
{sourceUrl, bool asDSX = false, void onError(JaelError error)?}) { {sourceUrl, bool asDSX = false, void Function(JaelError error)? onError}) {
var scanner = scan(text, sourceUrl: sourceUrl, asDSX: asDSX); var scanner = scan(text, sourceUrl: sourceUrl, asDSX: asDSX);
//scanner.tokens.forEach(print); //scanner.tokens.forEach(print);
@ -56,12 +57,12 @@ class Renderer {
..writeln('<li>') ..writeln('<li>')
..indent() ..indent()
..writeln( ..writeln(
'<b>$type:</b> ${error.span!.start.toolString}: ${error.message}') '<b>$type:</b> ${error.span.start.toolString}: ${error.message}')
..writeln('<br>') ..writeln('<br>')
..writeln( ..writeln(
'<span style="color: red;">' + '<span style="color: red;">' +
htmlEscape htmlEscape
.convert(error.span!.highlight(color: false)) .convert(error.span.highlight(color: false))
.replaceAll('\n', '<br>') + .replaceAll('\n', '<br>') +
'</span>', '</span>',
) )
@ -161,7 +162,7 @@ class Renderer {
buffer.writeln('>'); buffer.writeln('>');
buffer.indent(); buffer.indent();
for (int i = 0; i < element.children.length; i++) { for (var i = 0; i < element.children.length; i++) {
var child = element.children.elementAt(i); var child = element.children.elementAt(i);
renderElementChild(element, child, buffer, childScope, html5, i, renderElementChild(element, child, buffer, childScope, html5, i,
element.children.length); element.children.length);
@ -278,7 +279,7 @@ class Renderer {
?.value ?.value
?.compute(scope); ?.compute(scope);
if (comparison == value) { if (comparison == value) {
for (int i = 0; i < child.children.length; i++) { for (var i = 0; i < child.children.length; i++) {
var c = child.children.elementAt(i); var c = child.children.elementAt(i);
renderElementChild( renderElementChild(
element, c, buffer, scope, html5, i, child.children.length); element, c, buffer, scope, html5, i, child.children.length);
@ -303,11 +304,11 @@ class Renderer {
SymbolTable scope, bool html5, int index, int total) { SymbolTable scope, bool html5, int index, int total) {
if (child is Text && parent.tagName.name != 'textarea') { if (child is Text && parent.tagName.name != 'textarea') {
if (index == 0) { if (index == 0) {
buffer.write(child.span!.text.trimLeft()); buffer.write(child.span.text?.trimLeft());
} else if (index == total - 1) { } else if (index == total - 1) {
buffer.write(child.span!.text.trimRight()); buffer.write(child.span.text?.trimRight());
} else { } else {
buffer.write(child.span!.text); buffer.write(child.span.text);
} }
} else if (child is Interpolation) { } else if (child is Interpolation) {
var value = child.expression.compute(scope); var value = child.expression.compute(scope);
@ -369,7 +370,7 @@ class Renderer {
} }
if (renderAs == false) { if (renderAs == false) {
for (int i = 0; i < template!.children.length; i++) { for (var i = 0; i < template!.children.length; i++) {
var child = template.children.elementAt(i); var child = template.children.elementAt(i);
renderElementChild( renderElementChild(
element, child, buffer, scope, html5, i, element.children.length); element, child, buffer, scope, html5, i, element.children.length);

View file

@ -28,12 +28,12 @@ class ConditionalParselet implements InfixParselet {
const ConditionalParselet(); const ConditionalParselet();
@override @override
Expression? parse(Parser parser, Expression? left, Token? token) { Expression? parse(Parser parser, Expression left, Token token) {
var ifTrue = parser.parseExpression(0); var ifTrue = parser.parseExpression(0);
if (ifTrue == null) { if (ifTrue == null) {
parser.errors.add(JaelError(JaelErrorSeverity.error, parser.errors.add(JaelError(JaelErrorSeverity.error,
'Missing expression in conditional expression.', token!.span)); 'Missing expression in conditional expression.', token.span));
return null; return null;
} }
@ -48,7 +48,7 @@ class ConditionalParselet implements InfixParselet {
if (ifFalse == null) { if (ifFalse == null) {
parser.errors.add(JaelError(JaelErrorSeverity.error, parser.errors.add(JaelError(JaelErrorSeverity.error,
'Missing expression in conditional expression.', colon!.span)); 'Missing expression in conditional expression.', colon.span));
return null; return null;
} }
@ -57,19 +57,20 @@ class ConditionalParselet implements InfixParselet {
} }
class BinaryParselet implements InfixParselet { class BinaryParselet implements InfixParselet {
@override
final int precedence; final int precedence;
const BinaryParselet(this.precedence); const BinaryParselet(this.precedence);
@override @override
Expression? parse(Parser parser, Expression? left, Token? token) { Expression? parse(Parser parser, Expression left, Token token) {
var right = parser.parseExpression(precedence); var right = parser.parseExpression(precedence);
if (right == null) { if (right == null) {
if (token!.type != TokenType.gt) { if (token.type != TokenType.gt) {
parser.errors.add(JaelError( parser.errors.add(JaelError(
JaelErrorSeverity.error, JaelErrorSeverity.error,
'Missing expression after operator "${token.span!.text}", following expression ${left!.span!.text}.', 'Missing expression after operator "${token.span.text}", following expression ${left.span.text}.',
token.span)); token.span));
} }
return null; return null;
@ -86,10 +87,10 @@ class CallParselet implements InfixParselet {
int get precedence => 19; int get precedence => 19;
@override @override
Expression? parse(Parser parser, Expression? left, Token? token) { Expression? parse(Parser parser, Expression left, Token token) {
List<Expression> arguments = []; var arguments = <Expression>[];
List<NamedArgument> namedArguments = []; var namedArguments = <NamedArgument>[];
Expression? argument = parser.parseExpression(0); var argument = parser.parseExpression(0);
while (argument != null) { while (argument != null) {
arguments.add(argument); arguments.add(argument);
@ -98,7 +99,7 @@ class CallParselet implements InfixParselet {
argument = parser.parseExpression(0); argument = parser.parseExpression(0);
} }
NamedArgument? namedArgument = parser.parseNamedArgument(); var namedArgument = parser.parseNamedArgument();
while (namedArgument != null) { while (namedArgument != null) {
namedArguments.add(namedArgument); namedArguments.add(namedArgument);
@ -109,7 +110,7 @@ class CallParselet implements InfixParselet {
if (!parser.next(TokenType.rParen)) { if (!parser.next(TokenType.rParen)) {
var lastSpan = arguments.isEmpty ? null : arguments.last.span; var lastSpan = arguments.isEmpty ? null : arguments.last.span;
lastSpan ??= token!.span; lastSpan ??= token.span;
parser.errors.add(JaelError(JaelErrorSeverity.error, parser.errors.add(JaelError(JaelErrorSeverity.error,
'Missing ")" after argument list.', lastSpan)); 'Missing ")" after argument list.', lastSpan));
return null; return null;
@ -126,12 +127,12 @@ class IndexerParselet implements InfixParselet {
int get precedence => 19; int get precedence => 19;
@override @override
Expression? parse(Parser parser, Expression? left, Token? token) { Expression? parse(Parser parser, Expression left, Token token) {
var indexer = parser.parseExpression(0); var indexer = parser.parseExpression(0);
if (indexer == null) { if (indexer == null) {
parser.errors.add(JaelError( parser.errors.add(JaelError(
JaelErrorSeverity.error, 'Missing expression after "[".', left!.span)); JaelErrorSeverity.error, 'Missing expression after "[".', left.span));
return null; return null;
} }
@ -152,12 +153,12 @@ class MemberParselet implements InfixParselet {
int get precedence => 19; int get precedence => 19;
@override @override
Expression? parse(Parser parser, Expression? left, Token? token) { Expression? parse(Parser parser, Expression left, Token token) {
var name = parser.parseIdentifier(); var name = parser.parseIdentifier();
if (name == null) { if (name == null) {
parser.errors.add(JaelError(JaelErrorSeverity.error, parser.errors.add(JaelError(JaelErrorSeverity.error,
'Expected the name of a property following "."', token!.span)); 'Expected the name of a property following "."', token.span));
return null; return null;
} }

View file

@ -6,10 +6,10 @@ part 'infix.dart';
part 'prefix.dart'; part 'prefix.dart';
abstract class PrefixParselet { abstract class PrefixParselet {
Expression? parse(Parser parser, Token? token); Expression? parse(Parser parser, Token token);
} }
abstract class InfixParselet { abstract class InfixParselet {
int get precedence; int get precedence;
Expression? parse(Parser parser, Expression? left, Token? token); Expression? parse(Parser parser, Expression left, Token token);
} }

View file

@ -16,15 +16,15 @@ class NotParselet implements PrefixParselet {
const NotParselet(); const NotParselet();
@override @override
Expression parse(Parser parser, Token? token) { Expression parse(Parser parser, Token token) {
var expression = parser.parseExpression(0); var expression = parser.parseExpression(0);
if (expression == null) { if (expression == null) {
parser.errors.add(JaelError(JaelErrorSeverity.error, parser.errors.add(JaelError(JaelErrorSeverity.error,
'Missing expression after "!" in negation expression.', token!.span)); 'Missing expression after "!" in negation expression.', token.span));
} }
return Negation(token, expression); return Negation(token, expression!);
} }
} }
@ -32,7 +32,7 @@ class NewParselet implements PrefixParselet {
const NewParselet(); const NewParselet();
@override @override
Expression? parse(Parser parser, Token? token) { Expression? parse(Parser parser, Token token) {
var call = parser.parseExpression(0); var call = parser.parseExpression(0);
if (call == null) { if (call == null) {
@ -57,31 +57,31 @@ class NumberParselet implements PrefixParselet {
const NumberParselet(); const NumberParselet();
@override @override
Expression parse(Parser parser, Token? token) => NumberLiteral(token); Expression parse(Parser parser, Token token) => NumberLiteral(token);
} }
class HexParselet implements PrefixParselet { class HexParselet implements PrefixParselet {
const HexParselet(); const HexParselet();
@override @override
Expression parse(Parser parser, Token? token) => HexLiteral(token); Expression parse(Parser parser, Token token) => HexLiteral(token);
} }
class StringParselet implements PrefixParselet { class StringParselet implements PrefixParselet {
const StringParselet(); const StringParselet();
@override @override
Expression parse(Parser parser, Token? token) => Expression parse(Parser parser, Token token) =>
StringLiteral(token, StringLiteral.parseValue(token!)); StringLiteral(token, StringLiteral.parseValue(token));
} }
class ArrayParselet implements PrefixParselet { class ArrayParselet implements PrefixParselet {
const ArrayParselet(); const ArrayParselet();
@override @override
Expression? parse(Parser parser, Token? token) { Expression? parse(Parser parser, Token token) {
List<Expression> items = []; var items = <Expression>[];
Expression? item = parser.parseExpression(0); var item = parser.parseExpression(0);
while (item != null) { while (item != null) {
items.add(item); items.add(item);
@ -92,7 +92,7 @@ class ArrayParselet implements PrefixParselet {
if (!parser.next(TokenType.rBracket)) { if (!parser.next(TokenType.rBracket)) {
var lastSpan = items.isEmpty ? null : items.last.span; var lastSpan = items.isEmpty ? null : items.last.span;
lastSpan ??= token!.span; lastSpan ??= token.span;
parser.errors.add(JaelError(JaelErrorSeverity.error, parser.errors.add(JaelError(JaelErrorSeverity.error,
'Missing "]" to terminate array literal.', lastSpan)); 'Missing "]" to terminate array literal.', lastSpan));
return null; return null;
@ -106,7 +106,7 @@ class MapParselet implements PrefixParselet {
const MapParselet(); const MapParselet();
@override @override
Expression? parse(Parser parser, Token? token) { Expression? parse(Parser parser, Token token) {
var pairs = <KeyValuePair>[]; var pairs = <KeyValuePair>[];
var pair = parser.parseKeyValuePair(); var pair = parser.parseKeyValuePair();
@ -118,7 +118,7 @@ class MapParselet implements PrefixParselet {
} }
if (!parser.next(TokenType.rCurly)) { if (!parser.next(TokenType.rCurly)) {
var lastSpan = pairs.isEmpty ? token!.span : pairs.last.span; var lastSpan = pairs.isEmpty ? token.span : pairs.last.span;
parser.errors.add(JaelError( parser.errors.add(JaelError(
JaelErrorSeverity.error, 'Missing "}" in map literal.', lastSpan)); JaelErrorSeverity.error, 'Missing "}" in map literal.', lastSpan));
return null; return null;
@ -132,7 +132,7 @@ class IdentifierParselet implements PrefixParselet {
const IdentifierParselet(); const IdentifierParselet();
@override @override
Expression parse(Parser parser, Token? token) => Identifier(token); Expression parse(Parser parser, Token token) => Identifier(token);
} }
class ParenthesisParselet implements PrefixParselet { class ParenthesisParselet implements PrefixParselet {

View file

@ -7,12 +7,12 @@ class Parser {
final Scanner scanner; final Scanner scanner;
final bool asDSX; final bool asDSX;
Token? _current; late Token _current;
int _index = -1; int _index = -1;
Parser(this.scanner, {this.asDSX = false}); Parser(this.scanner, {this.asDSX = false});
Token? get current => _current; Token get current => _current;
int _nextPrecedence() { int _nextPrecedence() {
var tok = peek(); var tok = peek();
@ -68,8 +68,11 @@ class Parser {
StringLiteral? implicitString() { StringLiteral? implicitString() {
if (next(TokenType.string)) { if (next(TokenType.string)) {
return prefixParselets[TokenType.string]!.parse(this, _current) var result = prefixParselets[TokenType.string]?.parse(this, _current);
as StringLiteral?; if (result != null) {
return result as StringLiteral;
}
return null;
} }
/*else if (next(TokenType.text)) { /*else if (next(TokenType.text)) {
@ -86,12 +89,14 @@ class Parser {
_index--; _index--;
return null; return null;
} }
var doctype = _current, html = parseIdentifier() as Token?; var doctype = _current;
if (html?.span?.text.toLowerCase() != 'html') { var html = parseIdentifier();
if (html == null || html.span.text?.toLowerCase() != 'html') {
errors.add(JaelError( errors.add(JaelError(
JaelErrorSeverity.error, JaelErrorSeverity.error,
'Expected "html" in doctype declaration.', 'Expected "html" in doctype declaration.',
html?.span ?? doctype!.span)); html?.span ?? doctype.span));
return null; return null;
} }
@ -99,19 +104,23 @@ class Parser {
if (public == null) { if (public == null) {
if (!next(TokenType.gt)) { if (!next(TokenType.gt)) {
errors.add(JaelError(JaelErrorSeverity.error, errors.add(JaelError(JaelErrorSeverity.error,
'Expected ">" in doctype declaration.', html!.span)); 'Expected ">" in doctype declaration.', html.span));
// ?? doctype.span));
return null; return null;
} }
return Doctype( return Doctype(lt, doctype, html, null, null, null, _current);
lt, doctype, html as Identifier?, null, null, null, _current);
} }
if (public.span?.text.toLowerCase() != 'public') { if (public.span.text?.toLowerCase() != 'public') {
errors.add(JaelError( //errors.add(JaelError(
JaelErrorSeverity.error, // JaelErrorSeverity.error,
'Expected "public" in doctype declaration.', // 'Expected "public" in doctype declaration.',
public.span ?? html!.span)); // public!.span ?? html?.span));
errors.add(JaelError(JaelErrorSeverity.error,
'Expected "public" in doctype declaration.', public.span));
return null; return null;
} }
@ -123,24 +132,23 @@ class Parser {
return null; return null;
} }
var name = stringParser!.parse(this, _current) as StringLiteral?; var name = stringParser?.parse(this, _current) as StringLiteral;
if (!next(TokenType.string)) { if (!next(TokenType.string)) {
errors.add(JaelError(JaelErrorSeverity.error, errors.add(JaelError(JaelErrorSeverity.error,
'Expected string in doctype declaration.', name!.span)); 'Expected string in doctype declaration.', name.span));
return null; return null;
} }
var url = stringParser.parse(this, _current) as StringLiteral?; var url = stringParser?.parse(this, _current) as StringLiteral;
if (!next(TokenType.gt)) { if (!next(TokenType.gt)) {
errors.add(JaelError(JaelErrorSeverity.error, errors.add(JaelError(JaelErrorSeverity.error,
'Expected ">" in doctype declaration.', url!.span)); 'Expected ">" in doctype declaration.', url.span));
return null; return null;
} }
return Doctype( return Doctype(lt, doctype, html, public, name, url, _current);
lt, doctype, html as Identifier?, public, name, url, _current);
} }
ElementChild? parseElementChild() => ElementChild? parseElementChild() =>
@ -162,7 +170,7 @@ class Parser {
if (expression == null) { if (expression == null) {
errors.add(JaelError(JaelErrorSeverity.error, errors.add(JaelError(JaelErrorSeverity.error,
'Missing expression in interpolation.', doubleCurlyL!.span)); 'Missing expression in interpolation.', doubleCurlyL.span));
return null; return null;
} }
@ -190,7 +198,7 @@ class Parser {
if (tagName == null) { if (tagName == null) {
errors.add( errors.add(
JaelError(JaelErrorSeverity.error, 'Missing tag name.', lt!.span)); JaelError(JaelErrorSeverity.error, 'Missing tag name.', lt.span));
return null; return null;
} }
@ -208,7 +216,7 @@ class Parser {
if (!next(TokenType.gt)) { if (!next(TokenType.gt)) {
errors.add(JaelError(JaelErrorSeverity.error, errors.add(JaelError(JaelErrorSeverity.error,
'Missing ">" in self-closing "${tagName.name}" tag.', slash!.span)); 'Missing ">" in self-closing "${tagName.name}" tag.', slash.span));
return null; return null;
} }
@ -252,7 +260,7 @@ class Parser {
if (!next(TokenType.slash)) { if (!next(TokenType.slash)) {
errors.add(JaelError(JaelErrorSeverity.error, errors.add(JaelError(JaelErrorSeverity.error,
'Missing "/" in "${tagName.name}" closing tag.', lt2!.span)); 'Missing "/" in "${tagName.name}" closing tag.', lt2.span));
return null; return null;
} }
@ -263,15 +271,15 @@ class Parser {
errors.add(JaelError( errors.add(JaelError(
JaelErrorSeverity.error, JaelErrorSeverity.error,
'Missing "${tagName.name}" in "${tagName.name}" closing tag.', 'Missing "${tagName.name}" in "${tagName.name}" closing tag.',
slash!.span)); slash.span));
return null; return null;
} }
if (tagName2.name != tagName.name) { if (tagName2.name != tagName.name) {
errors.add(JaelError( errors.add(JaelError(
JaelErrorSeverity.error, JaelErrorSeverity.error,
'Mismatched closing tags. Expected "${tagName.span!.text}"; got "${tagName2.name}" instead.', 'Mismatched closing tags. Expected "${tagName.span.text}"; got "${tagName2.name}" instead.',
lt2!.span)); lt2.span));
return null; return null;
} }
@ -292,7 +300,7 @@ class Parser {
if ((id = parseIdentifier()) != null) { if ((id = parseIdentifier()) != null) {
// Nothing // Nothing
} else if (next(TokenType.string)) { } else if (next(TokenType.string)) {
string = StringLiteral(_current, StringLiteral.parseValue(_current!)); string = StringLiteral(_current, StringLiteral.parseValue(_current));
} else { } else {
return null; return null;
} }
@ -342,12 +350,12 @@ class Parser {
for (var type in prefixParselets.keys) { for (var type in prefixParselets.keys) {
if (next(type)) { if (next(type)) {
var left = prefixParselets[type]!.parse(this, _current); var left = prefixParselets[type]?.parse(this, _current);
while (precedence < _nextPrecedence()) { while (precedence < _nextPrecedence()) {
_current = scanner.tokens[++_index]; _current = scanner.tokens[++_index];
if (_current!.type == TokenType.slash && if (_current.type == TokenType.slash &&
peek()?.type == TokenType.gt) { peek()?.type == TokenType.gt) {
// Handle `/>` // Handle `/>`
// //
@ -357,11 +365,14 @@ class Parser {
return left; return left;
} }
var infix = infixParselets[_current!.type]!; var infix = infixParselets[_current.type]!;
var newLeft = infix.parse(this, left, _current); Expression? newLeft;
if (left != null) {
newLeft = infix.parse(this, left, _current);
}
if (newLeft == null) { if (newLeft == null) {
if (_current!.type == TokenType.gt) _index--; if (_current.type == TokenType.gt) _index--;
return left; return left;
} }
left = newLeft; left = newLeft;
@ -388,11 +399,11 @@ class Parser {
if (value == null) { if (value == null) {
errors.add(JaelError(JaelErrorSeverity.error, errors.add(JaelError(JaelErrorSeverity.error,
'Missing expression in key-value pair.', colon!.span)); 'Missing expression in key-value pair.', colon.span));
return null; return null;
} }
return KeyValuePair(key, colon, value as Expression?); return KeyValuePair(key, colon, value as Expression);
} }
NamedArgument? parseNamedArgument() { NamedArgument? parseNamedArgument() {
@ -409,7 +420,7 @@ class Parser {
if (value == null) { if (value == null) {
errors.add(JaelError(JaelErrorSeverity.error, errors.add(JaelError(JaelErrorSeverity.error,
'Missing expression in named argument.', colon!.span)); 'Missing expression in named argument.', colon.span));
return null; return null;
} }

View file

@ -55,7 +55,7 @@ final Map<Pattern, TokenType> _expressionPatterns = {
'.': TokenType.dot, '.': TokenType.dot,
'??': TokenType.elvis, '??': TokenType.elvis,
'?.': TokenType.elvis_dot, '?.': TokenType.elvis_dot,
'=': TokenType.equals, //'=': TokenType.equals,
'!': TokenType.exclamation, '!': TokenType.exclamation,
'-': TokenType.minus, '-': TokenType.minus,
'%': TokenType.percent, '%': TokenType.percent,
@ -66,14 +66,14 @@ final Map<Pattern, TokenType> _expressionPatterns = {
'}': TokenType.rCurly, '}': TokenType.rCurly,
'(': TokenType.lParen, '(': TokenType.lParen,
')': TokenType.rParen, ')': TokenType.rParen,
'/': TokenType.slash, //'/': TokenType.slash,
'<': TokenType.lt, //'<': TokenType.lt,
'<=': TokenType.lte, '<=': TokenType.lte,
'>': TokenType.gt, //'>': TokenType.gt,
'>=': TokenType.gte, '>=': TokenType.gte,
'==': TokenType.equ, '==': TokenType.equ,
'!=': TokenType.nequ, //'!=': TokenType.nequ,
'=': TokenType.equals, //'=': TokenType.equals,
RegExp(r'-?[0-9]+(\.[0-9]+)?([Ee][0-9]+)?'): TokenType.number, RegExp(r'-?[0-9]+(\.[0-9]+)?([Ee][0-9]+)?'): TokenType.number,
RegExp(r'0x[A-Fa-f0-9]+'): TokenType.hex, RegExp(r'0x[A-Fa-f0-9]+'): TokenType.hex,
_string1: TokenType.string, _string1: TokenType.string,
@ -82,47 +82,50 @@ final Map<Pattern, TokenType> _expressionPatterns = {
}; };
class _Scanner implements Scanner { class _Scanner implements Scanner {
@override
final List<JaelError> errors = []; final List<JaelError> errors = [];
@override
final List<Token> tokens = []; final List<Token> tokens = [];
_ScannerState state = _ScannerState.html; _ScannerState state = _ScannerState.html;
final Queue<String?> openTags = Queue(); final Queue<String?> openTags = Queue();
SpanScanner? _scanner; late SpanScanner _scanner;
_Scanner(String text, sourceUrl) { _Scanner(String text, sourceUrl) {
_scanner = SpanScanner(text, sourceUrl: sourceUrl); _scanner = SpanScanner(text, sourceUrl: sourceUrl);
} }
void scan({bool asDSX = false}) { void scan({bool asDSX = false}) {
while (!_scanner!.isDone) { while (!_scanner.isDone) {
if (state == _ScannerState.html) { if (state == _ScannerState.html) {
scanHtml(asDSX); scanHtml(asDSX);
} else if (state == _ScannerState.freeText) { } else if (state == _ScannerState.freeText) {
// Just keep parsing until we hit "</" // Just keep parsing until we hit "</"
var start = _scanner!.state, end = start; var start = _scanner.state, end = start;
while (!_scanner!.isDone) { while (!_scanner.isDone) {
// Skip through comments // Skip through comments
if (_scanner!.scan(_htmlComment)) continue; if (_scanner.scan(_htmlComment)) continue;
// Break on {{ or { // Break on {{ or {
if (_scanner!.matches(asDSX ? '{' : '{{')) { if (_scanner.matches(asDSX ? '{' : '{{')) {
state = _ScannerState.html; state = _ScannerState.html;
//_scanner.position--; //_scanner.position--;
break; break;
} }
var ch = _scanner!.readChar(); var ch = _scanner.readChar();
if (ch == $lt) { if (ch == $lt) {
// && !_scanner.isDone) { // && !_scanner.isDone) {
if (_scanner!.matches('/')) { if (_scanner.matches('/')) {
// If we reached "</", backtrack and break into HTML // If we reached "</", backtrack and break into HTML
openTags.removeFirst(); openTags.removeFirst();
_scanner!.position--; _scanner.position--;
state = _ScannerState.html; state = _ScannerState.html;
break; break;
} else if (_scanner!.matches(_id)) { } else if (_scanner.matches(_id)) {
// Also break when we reach <foo. // Also break when we reach <foo.
// //
// HOWEVER, that is also JavaScript. So we must // HOWEVER, that is also JavaScript. So we must
@ -132,26 +135,26 @@ class _Scanner implements Scanner {
if (!shouldBreak) { if (!shouldBreak) {
// Try to see if we are closing a script tag // Try to see if we are closing a script tag
var replay = _scanner!.state; var replay = _scanner.state;
_scanner _scanner
?..readChar() ..readChar()
..scan(_whitespace); ..scan(_whitespace);
//print(_scanner.emptySpan.highlight()); //print(_scanner.emptySpan.highlight());
if (_scanner!.matches(_id)) { if (_scanner.matches(_id)) {
//print(_scanner.lastMatch[0]); //print(_scanner.lastMatch[0]);
shouldBreak = _scanner!.lastMatch![0] == 'script'; shouldBreak = _scanner.lastMatch?[0] == 'script';
_scanner!.position--; _scanner.position--;
} }
if (!shouldBreak) { if (!shouldBreak) {
_scanner!.state = replay; _scanner.state = replay;
} }
} }
if (shouldBreak) { if (shouldBreak) {
openTags.removeFirst(); openTags.removeFirst();
_scanner!.position--; _scanner.position--;
state = _ScannerState.html; state = _ScannerState.html;
break; break;
} }
@ -159,12 +162,12 @@ class _Scanner implements Scanner {
} }
// Otherwise, just add to the "buffer" // Otherwise, just add to the "buffer"
end = _scanner!.state; end = _scanner.state;
} }
var span = _scanner!.spanFrom(start, end); var span = _scanner.spanFrom(start, end);
if (span.text.isNotEmpty) { if (span.text?.isNotEmpty == true) {
tokens.add(Token(TokenType.text, span, null)); tokens.add(Token(TokenType.text, span, null));
} }
} }
@ -182,35 +185,41 @@ class _Scanner implements Scanner {
while (true) { while (true) {
// Scan whitespace // Scan whitespace
_scanner!.scan(_whitespace); _scanner.scan(_whitespace);
_expressionPatterns.forEach((pattern, type) { _expressionPatterns.forEach((pattern, type) {
if (_scanner!.matches(pattern)) { if (_scanner.matches(pattern)) {
potential if (_scanner.lastSpan != null) {
.add(Token(type, _scanner!.lastSpan, _scanner!.lastMatch)); potential
.add(Token(type, _scanner.lastSpan!, _scanner.lastMatch));
} else {
// TODO: To be relooked
}
} }
}); });
potential.sort((a, b) => b.span!.length.compareTo(a.span!.length)); potential.sort((a, b) => b.span.length.compareTo(a.span.length));
if (potential.isEmpty) break; if (potential.isEmpty) break;
var token = potential.first; var token = potential.first;
tokens.add(token); tokens.add(token);
_scanner!.scan(token.span!.text); if (token.span.text != null) {
_scanner.scan(token.span.text!);
}
if (token.type == TokenType.lt) { if (token.type == TokenType.lt) {
brackets.addFirst(token); brackets.addFirst(token);
// Try to see if we are at a tag. // Try to see if we are at a tag.
var replay = _scanner!.state; var replay = _scanner.state;
_scanner!.scan(_whitespace); _scanner.scan(_whitespace);
if (_scanner!.matches(_id)) { if (_scanner.matches(_id)) {
openTags.addFirst(_scanner!.lastMatch![0]); openTags.addFirst(_scanner.lastMatch![0]);
} else { } else {
_scanner!.state = replay; _scanner.state = replay;
} }
} else if (token.type == TokenType.slash) { } else if (token.type == TokenType.slash) {
// Only push if we're at </foo // Only push if we're at </foo
@ -226,11 +235,11 @@ class _Scanner implements Scanner {
brackets.removeFirst(); brackets.removeFirst();
// Now, ONLY continue parsing HTML if the next character is '<'. // Now, ONLY continue parsing HTML if the next character is '<'.
var replay = _scanner!.state; var replay = _scanner.state;
_scanner!.scan(_whitespace); _scanner.scan(_whitespace);
if (!_scanner!.matches('<')) { if (!_scanner.matches('<')) {
_scanner!.state = replay; _scanner.state = replay;
state = _ScannerState.freeText; state = _ScannerState.freeText;
break; break;
} }
@ -241,11 +250,11 @@ class _Scanner implements Scanner {
// We're at foo>, try to parse text? // We're at foo>, try to parse text?
brackets.removeFirst(); brackets.removeFirst();
var replay = _scanner!.state; var replay = _scanner.state;
_scanner!.scan(_whitespace); _scanner.scan(_whitespace);
if (!_scanner!.matches('<')) { if (!_scanner.matches('<')) {
_scanner!.state = replay; _scanner.state = replay;
state = _ScannerState.freeText; state = _ScannerState.freeText;
break; break;
} }
@ -259,7 +268,7 @@ class _Scanner implements Scanner {
potential.clear(); potential.clear();
} }
} }
} while (brackets.isNotEmpty && !_scanner!.isDone); } while (brackets.isNotEmpty && !_scanner.isDone);
state = _ScannerState.freeText; state = _ScannerState.freeText;
} }

View file

@ -1,5 +1,5 @@
name: jael name: jael
version: 3.0.0 version: 4.0.0
description: A simple server-side HTML templating engine for Dart. Comparable to Blade or Liquid. description: A simple server-side HTML templating engine for Dart. Comparable to Blade or Liquid.
author: Tobe O <thosakwe@gmail.com> author: Tobe O <thosakwe@gmail.com>
homepage: https://docs.angel-dart.dev/packages/front-end/jael homepage: https://docs.angel-dart.dev/packages/front-end/jael

View file

@ -16,9 +16,9 @@ void main() {
expect(foo.getAttribute('bar')?.value?.compute(null), 'baz'); expect(foo.getAttribute('bar')?.value?.compute(null), 'baz');
expect( expect(
foo foo
.getAttribute('yes')! .getAttribute('yes')
.value! ?.value
.compute(SymbolTable(values: {'no': 'maybe'})), ?.compute(SymbolTable(values: {'no': 'maybe'})),
'maybe'); 'maybe');
}); });

View file

@ -3,7 +3,7 @@ import 'package:jael/jael.dart' as jael;
import 'package:symbol_table/symbol_table.dart'; import 'package:symbol_table/symbol_table.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
main() { void main() {
test('attribute binding', () { test('attribute binding', () {
const template = ''' const template = '''
<html> <html>

View file

@ -19,6 +19,6 @@ class _IsToken extends Matcher {
bool matches(item, Map matchState) { bool matches(item, Map matchState) {
return item is Token && return item is Token &&
item.type == type && item.type == type &&
(text == null || item.span!.text == text); (text == null || item.span.text == text);
} }
} }

View file

@ -3,7 +3,7 @@ import 'package:jael/src/text/scanner.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'common.dart'; import 'common.dart';
main() { void main() {
test('plain html', () { test('plain html', () {
var tokens = scan('<img src="foo.png" />', sourceUrl: 'test.jael').tokens; var tokens = scan('<img src="foo.png" />', sourceUrl: 'test.jael').tokens;
tokens.forEach(print); tokens.forEach(print);