Skip to content
This repository has been archived by the owner on May 15, 2023. It is now read-only.

Commit

Permalink
Support non-nullability (#40)
Browse files Browse the repository at this point in the history
  • Loading branch information
nex3 committed May 18, 2021
1 parent 54d067e commit 93bc86f
Show file tree
Hide file tree
Showing 18 changed files with 77 additions and 90 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 1.0.0-beta.8

* Internal changes only.
22 changes: 10 additions & 12 deletions bin/dart_sass_embedded.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,12 @@ void main(List<String> args) {
request.style == InboundMessage_CompileRequest_OutputStyle.COMPRESSED
? sass.OutputStyle.compressed
: sass.OutputStyle.expanded;
var color = request.alertColor ?? false;
var ascii = request.alertAscii ?? false;
var logger = Logger(dispatcher, request.id, color: color, ascii: ascii);
var logger = Logger(dispatcher, request.id,
color: request.alertColor, ascii: request.alertAscii);

try {
String result;
source_maps.SingleMapping sourceMap;
source_maps.SingleMapping? sourceMap;
var sourceMapCallback = request.sourceMap
? (source_maps.SingleMapping map) => sourceMap = map
: null;
Expand All @@ -61,7 +60,7 @@ void main(List<String> args) {
case InboundMessage_CompileRequest_Input.string:
var input = request.string;
result = sass.compileString(input.source,
color: color,
color: request.alertColor,
logger: logger,
importers: importers,
importer: _decodeImporter(dispatcher, request, input.importer),
Expand All @@ -75,7 +74,7 @@ void main(List<String> args) {
case InboundMessage_CompileRequest_Input.path:
try {
result = sass.compile(request.path,
color: color,
color: request.alertColor,
logger: logger,
importers: importers,
functions: globalFunctions,
Expand All @@ -97,11 +96,13 @@ void main(List<String> args) {
var success = OutboundMessage_CompileResponse_CompileSuccess()
..css = result;
if (sourceMap != null) {
success.sourceMap = json.encode(sourceMap.toJson());
// dart-lang/language#1536
success.sourceMap = json.encode(sourceMap!.toJson());
}
return OutboundMessage_CompileResponse()..success = success;
} on sass.SassException catch (error) {
var formatted = withGlyphs(() => error.toString(color: color),
var formatted = withGlyphs(
() => error.toString(color: request.alertColor),
ascii: request.alertAscii);
return OutboundMessage_CompileResponse()
..failure = (OutboundMessage_CompileResponse_CompileFailure()
Expand All @@ -114,7 +115,7 @@ void main(List<String> args) {
}

/// Converts [importer] into an [Importer].
sass.Importer _decodeImporter(
sass.Importer? _decodeImporter(
Dispatcher dispatcher,
InboundMessage_CompileRequest request,
InboundMessage_CompileRequest_Importer importer) {
Expand All @@ -131,7 +132,4 @@ sass.Importer _decodeImporter(
case InboundMessage_CompileRequest_Importer_Importer.notSet:
return null;
}

// dart-lang/sdk#38790
throw "Unknown Importer.importer $importer.";
}
8 changes: 4 additions & 4 deletions lib/src/dispatcher.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class Dispatcher {
/// The completers are located at indexes in this list matching the request
/// IDs. `null` elements indicate IDs whose requests have been responded to,
/// and which are therefore free to re-use.
final _outstandingRequests = <Completer<GeneratedMessage>>[];
final _outstandingRequests = <Completer<GeneratedMessage>?>[];

/// Creates a [Dispatcher] that sends and receives encoded protocol buffers
/// over [channel].
Expand All @@ -47,7 +47,7 @@ class Dispatcher {
// for new input.
await Future.value();

InboundMessage message;
InboundMessage? message;
try {
try {
message = InboundMessage.fromBuffer(binaryMessage);
Expand Down Expand Up @@ -182,7 +182,7 @@ class Dispatcher {

/// Returns the id for [message] if it it's a request, or `null`
/// otherwise.
int _inboundId(InboundMessage message) {
int? _inboundId(InboundMessage? message) {
if (message == null) return null;
switch (message.whichMessage()) {
case InboundMessage_Message.compileRequest:
Expand Down Expand Up @@ -210,7 +210,7 @@ class Dispatcher {
message.functionCallRequest.id = id;
break;
default:
return null;
break;
}
}
}
2 changes: 1 addition & 1 deletion lib/src/function_registry.dart
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,5 @@ class FunctionRegistry {
/// Returns the compiler-side function associated with [id].
///
/// If no such function exists, returns `null`.
sass.SassFunction operator [](int id) => _functionsById[id];
sass.SassFunction? operator [](int id) => _functionsById[id];
}
7 changes: 2 additions & 5 deletions lib/src/host_callable.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import 'value.dart';
/// Throws a [ProtocolError] if [signature] is invalid.
sass.Callable hostCallable(Dispatcher dispatcher, FunctionRegistry functions,
int compilationId, String signature,
{int id}) {
{int? id}) {
var openParen = signature.indexOf('(');
if (openParen == -1) {
throw paramsError(
Expand All @@ -38,7 +38,7 @@ sass.Callable hostCallable(Dispatcher dispatcher, FunctionRegistry functions,

var name = signature.substring(0, openParen);
try {
return sass.Callable(
return sass.Callable.function(
name, signature.substring(openParen + 1, signature.length - 1),
(arguments) {
var request = OutboundMessage_FunctionCallRequest()
Expand Down Expand Up @@ -66,9 +66,6 @@ sass.Callable hostCallable(Dispatcher dispatcher, FunctionRegistry functions,
case InboundMessage_FunctionCallResponse_Result.notSet:
throw mandatoryError('FunctionCallResponse.result');
}

// dart-lang/sdk#38790
throw "Unknown FunctionCallResponse.result $response.";
} on ProtocolError catch (error) {
error.id = errorId;
stderr.writeln("Host caused ${error.type.name.toLowerCase()} error: "
Expand Down
13 changes: 2 additions & 11 deletions lib/src/importer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import 'dart:cli';

import 'package:meta/meta.dart';
import 'package:sass/sass.dart' as sass;

import 'dispatcher.dart';
Expand All @@ -24,7 +23,7 @@ class Importer extends sass.Importer {

Importer(this._dispatcher, this._compilationId, this._importerId);

Uri canonicalize(Uri url) {
Uri? canonicalize(Uri url) {
return waitFor(() async {
var response = await _dispatcher
.sendCanonicalizeRequest(OutboundMessage_CanonicalizeRequest()
Expand All @@ -42,9 +41,6 @@ class Importer extends sass.Importer {
case InboundMessage_CanonicalizeResponse_Result.notSet:
return null;
}

// dart-lang/sdk#38790
throw "Unknown CanonicalizeResponse.result $response.";
}());
}

Expand All @@ -70,11 +66,7 @@ class Importer extends sass.Importer {

case InboundMessage_ImportResponse_Result.notSet:
_sendAndThrow(mandatoryError("ImportResponse.result"));
break; // dart-lang/sdk#34048
}

// dart-lang/sdk#38790
throw "Unknown ImporterResponse.result $response.";
}());
}

Expand All @@ -96,8 +88,7 @@ class Importer extends sass.Importer {

/// Sends [error] to the remote endpoint, and also throws it so that the Sass
/// compilation fails.
@alwaysThrows
void _sendAndThrow(ProtocolError error) {
Never _sendAndThrow(ProtocolError error) {
_dispatcher.sendError(error);
throw "Protocol error: ${error.message}";
}
Expand Down
4 changes: 2 additions & 2 deletions lib/src/logger.dart
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ class Logger implements sass.Logger {
}

void warn(String message,
{FileSpan span, Trace trace, bool deprecation = false}) {
{FileSpan? span, Trace? trace, bool deprecation = false}) {
var formatted = withGlyphs(() {
var buffer = new StringBuffer();
var buffer = StringBuffer();
if (_color) {
buffer.write('\u001b[33m\u001b[1m');
if (deprecation) buffer.write('Deprecation ');
Expand Down
21 changes: 11 additions & 10 deletions lib/src/util/length_delimited_transformer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,24 @@ final StreamChannelTransformer<Uint8List, List<int>> lengthDelimited =
final lengthDelimitedDecoder =
StreamTransformer<List<int>, Uint8List>.fromBind((stream) {
// The number of bits we've consumed so far to fill out [nextMessageLength].
int nextMessageLengthBits = 0;
var nextMessageLengthBits = 0;

// The length of the next message, in bytes.
//
// This is built up from a [varint]. Once it's fully consumed, [buffer] is
// initialized.
//
// [varint]: https://developers.google.com/protocol-buffers/docs/encoding#varints
int nextMessageLength = 0;
var nextMessageLength = 0;

// The buffer into which the packet data itself is written. Initialized once
// [nextMessageLength] is known.
Uint8List buffer;
Uint8List? buffer;

// The index of the next byte to write to [buffer]. Once this is equal to
// [buffer.length] (or equivalently [nextMessageLength]), the full packet is
// available.
int bufferIndex;
var bufferIndex = 0;

// It seems a little silly to use a nested [StreamTransformer] here, but we
// need the outer one to establish a closure context so we can share state
Expand All @@ -54,6 +54,8 @@ final lengthDelimitedDecoder =
var i = 0;

while (i < chunk.length) {
var buffer_ = buffer; // dart-lang/language#1536

// We can be in one of two states here:
//
// * [buffer] is `null`, in which case we're adding data to
Expand All @@ -63,7 +65,7 @@ final lengthDelimitedDecoder =
// * [buffer] is not `null`, in which case we're waiting for [buffer] to
// have [nextMessageLength] bytes in it before we send it to
// [queue.local.sink] and start waiting for the next message.
if (buffer == null) {
if (buffer_ == null) {
var byte = chunk[i];

// Varints encode data in the 7 lower bits of each byte, which we access
Expand All @@ -79,7 +81,7 @@ final lengthDelimitedDecoder =

// Otherwise, [nextMessageLength] is now finalized and we can allocate
// the data buffer.
buffer = Uint8List(nextMessageLength);
buffer_ = buffer = Uint8List(nextMessageLength);
bufferIndex = 0;
}

Expand All @@ -88,18 +90,17 @@ final lengthDelimitedDecoder =
// message after the current one) or more than the chunk has available (if
// the current message is split across multiple chunks).
var bytesToWrite =
math.min(buffer.length - bufferIndex, chunk.length - i);
buffer.setRange(bufferIndex, bufferIndex + bytesToWrite, chunk, i);
math.min(buffer_.length - bufferIndex, chunk.length - i);
buffer_.setRange(bufferIndex, bufferIndex + bytesToWrite, chunk, i);
i += bytesToWrite;
bufferIndex += bytesToWrite;
if (bufferIndex < nextMessageLength) return;

// Once we've filled the buffer, emit it and reset our state.
sink.add(buffer);
sink.add(buffer_);
nextMessageLength = 0;
nextMessageLengthBits = 0;
buffer = null;
bufferIndex = null;
}
}));
});
Expand Down
3 changes: 1 addition & 2 deletions lib/src/utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// MIT-style license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.

import 'package:meta/meta.dart';
import 'package:sass/sass.dart' as sass;
import 'package:source_span/source_span.dart';
import 'package:term_glyph/term_glyph.dart' as term_glyph;
Expand Down Expand Up @@ -66,7 +65,7 @@ String indent(String string, int indentation) =>

/// Returns the result of running [callback] with the global ASCII config set
/// to [ascii].
T withGlyphs<T>(T callback(), {@required bool ascii}) {
T withGlyphs<T>(T callback(), {required bool ascii}) {
var currentConfig = term_glyph.ascii;
term_glyph.ascii = ascii;
var result = callback();
Expand Down
5 changes: 0 additions & 5 deletions lib/src/value.dart
Original file line number Diff line number Diff line change
Expand Up @@ -166,15 +166,10 @@ sass.Value deprotofyValue(Dispatcher dispatcher, FunctionRegistry functions,
default:
throw "Unknown Value.singleton ${value.singleton}";
}
// dart-lang/sdk#39304
throw "Unreachable"; // ignore: dead_code

case Value_Value.notSet:
throw mandatoryError("Value.value");
}

// dart-lang/sdk#38790
throw "Unknown Value.value $value.";
}

/// Converts [separator] to its Sass representation.
Expand Down
14 changes: 7 additions & 7 deletions pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
name: sass_embedded
version: 1.0.0-beta.7
version: 1.0.0-dev
description: An implementation of the Sass embedded protocol using Dart Sass.
author: Sass Team
homepage: https://github.com/sass/dart-sass-embedded

environment:
sdk: '>=2.10.0 <3.0.0'
sdk: '>=2.12.0 <3.0.0'

executables:
dart-sass-embedded: dart_sass_embedded

dependencies:
async: ">=1.13.0 <3.0.0"
meta: ^1.1.0
protobuf: ^1.0.0
sass: ^1.21.0
protobuf: ^2.0.0
sass: ^1.25.0
source_maps: ^0.10.5
source_span: ^1.1.0
stack_trace: ^1.6.0
Expand All @@ -23,8 +23,8 @@ dependencies:

dev_dependencies:
cli_pkg: ^1.2.0
grinder: ^0.8.0
protoc_plugin: ^19.0.0
grinder: ^0.9.0
protoc_plugin: ^20.0.0
path: ^1.6.0
test: ^1.0.0
test_descriptor: ^1.0.0
test_descriptor: ^2.0.0
17 changes: 10 additions & 7 deletions test/embedded_process.dart
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ class EmbeddedProcess {

/// A [StreamQueue] that emits each outbound protocol buffer from the process.
StreamQueue<OutboundMessage> get outbound => _outbound;
StreamQueue<OutboundMessage> _outbound;
late StreamQueue<OutboundMessage> _outbound;

/// A [StreamQueue] that emits each line of stderr from the process.
StreamQueue<String> get stderr => _stderr;
StreamQueue<String> _stderr;
late StreamQueue<String> _stderr;

/// A splitter that can emit new copies of [outbound].
final StreamSplitter<OutboundMessage> _outboundSplitter;
Expand All @@ -49,7 +49,7 @@ class EmbeddedProcess {
final _log = <String>[];

/// Whether [_log] has been passed to [printOnFailure] yet.
bool _loggedOutput = false;
var _loggedOutput = false;

/// Returns a [Future] which completes to the exit code of the process, once
/// it completes.
Expand All @@ -60,8 +60,11 @@ class EmbeddedProcess {

/// Completes to [_process]'s exit code if it's exited, otherwise completes to
/// `null` immediately.
Future<int> get _exitCodeOrNull async =>
await exitCode.timeout(Duration.zero, onTimeout: () => null);
Future<int?> get _exitCodeOrNull async {
var exitCode =
await this.exitCode.timeout(Duration.zero, onTimeout: () => -1);
return exitCode == -1 ? null : exitCode;
}

/// Starts a process.
///
Expand All @@ -73,8 +76,8 @@ class EmbeddedProcess {
/// [stderr] will be printed to the console as they appear. This is only
/// intended to be set temporarily to help when debugging test failures.
static Future<EmbeddedProcess> start(
{String workingDirectory,
Map<String, String> environment,
{String? workingDirectory,
Map<String, String>? environment,
bool includeParentEnvironment = true,
bool runInShell = false,
bool forwardOutput = false}) async {
Expand Down

0 comments on commit 93bc86f

Please sign in to comment.