Auto merge of #17390 - servo:untry, r=nox

Untry

<!-- Reviewable:start -->
This change is [<img src="https://reviewable.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/servo/servo/17390)
<!-- Reviewable:end -->
This commit is contained in:
bors-servo 2017-06-18 05:55:11 -07:00 committed by GitHub
commit 568ab55005
115 changed files with 978 additions and 990 deletions

View file

@ -436,7 +436,7 @@ impl BluetoothManager {
device_id: &str, device_id: &str,
filters: &BluetoothScanfilterSequence) filters: &BluetoothScanfilterSequence)
-> BluetoothResult<bool> { -> BluetoothResult<bool> {
let mut adapter = try!(self.get_adapter()); let mut adapter = self.get_adapter()?;
match self.get_device(&mut adapter, device_id) { match self.get_device(&mut adapter, device_id) {
Some(ref device) => Ok(matches_filters(device, filters)), Some(ref device) => Ok(matches_filters(device, filters)),
None => Ok(false), None => Ok(false),
@ -578,7 +578,7 @@ impl BluetoothManager {
options: RequestDeviceoptions) options: RequestDeviceoptions)
-> BluetoothResponseResult { -> BluetoothResponseResult {
// Step 6. // Step 6.
let mut adapter = try!(self.get_adapter()); let mut adapter = self.get_adapter()?;
// Step 7. // Step 7.
// Note: There are no requiredServiceUUIDS, we scan for all devices. // Note: There are no requiredServiceUUIDS, we scan for all devices.
@ -630,7 +630,7 @@ impl BluetoothManager {
if !self.device_is_cached(&device_id) { if !self.device_is_cached(&device_id) {
return Err(BluetoothError::Network); return Err(BluetoothError::Network);
} }
let mut adapter = try!(self.get_adapter()); let mut adapter = self.get_adapter()?;
// Step 5.1.1. // Step 5.1.1.
match self.get_device(&mut adapter, &device_id) { match self.get_device(&mut adapter, &device_id) {
@ -660,7 +660,7 @@ impl BluetoothManager {
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-disconnect // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-disconnect
fn gatt_server_disconnect(&mut self, device_id: String) -> BluetoothResult<()> { fn gatt_server_disconnect(&mut self, device_id: String) -> BluetoothResult<()> {
let mut adapter = try!(self.get_adapter()); let mut adapter = self.get_adapter()?;
match self.get_device(&mut adapter, &device_id) { match self.get_device(&mut adapter, &device_id) {
Some(d) => { Some(d) => {
// Step 2. // Step 2.
@ -687,7 +687,7 @@ impl BluetoothManager {
single: bool, single: bool,
child_type: GATTType) child_type: GATTType)
-> BluetoothResponseResult { -> BluetoothResponseResult {
let mut adapter = try!(self.get_adapter()); let mut adapter = self.get_adapter()?;
match child_type { match child_type {
GATTType::PrimaryService => { GATTType::PrimaryService => {
// Step 5. // Step 5.
@ -839,7 +839,7 @@ impl BluetoothManager {
fn read_value(&mut self, id: String) -> BluetoothResponseResult { fn read_value(&mut self, id: String) -> BluetoothResponseResult {
// (Characteristic) Step 5.2: Missing because it is optional. // (Characteristic) Step 5.2: Missing because it is optional.
// (Descriptor) Step 5.1: Missing because it is optional. // (Descriptor) Step 5.1: Missing because it is optional.
let mut adapter = try!(self.get_adapter()); let mut adapter = self.get_adapter()?;
// (Characteristic) Step 5.3. // (Characteristic) Step 5.3.
let mut value = self.get_gatt_characteristic(&mut adapter, &id) let mut value = self.get_gatt_characteristic(&mut adapter, &id)
@ -871,7 +871,7 @@ impl BluetoothManager {
fn write_value(&mut self, id: String, value: Vec<u8>) -> BluetoothResponseResult { fn write_value(&mut self, id: String, value: Vec<u8>) -> BluetoothResponseResult {
// (Characteristic) Step 7.2: Missing because it is optional. // (Characteristic) Step 7.2: Missing because it is optional.
// (Descriptor) Step 7.1: Missing because it is optional. // (Descriptor) Step 7.1: Missing because it is optional.
let mut adapter = try!(self.get_adapter()); let mut adapter = self.get_adapter()?;
// (Characteristic) Step 7.3. // (Characteristic) Step 7.3.
let mut result = self.get_gatt_characteristic(&mut adapter, &id) let mut result = self.get_gatt_characteristic(&mut adapter, &id)
@ -913,7 +913,7 @@ impl BluetoothManager {
} }
// (StartNotification) TODO: Step 7: Missing because it is optional. // (StartNotification) TODO: Step 7: Missing because it is optional.
let mut adapter = try!(self.get_adapter()); let mut adapter = self.get_adapter()?;
match self.get_gatt_characteristic(&mut adapter, &id) { match self.get_gatt_characteristic(&mut adapter, &id) {
Some(c) => { Some(c) => {
let result = match enable { let result = match enable {

View file

@ -129,9 +129,9 @@ fn generate_id() -> Uuid {
// Set the adapter's name, is_powered and is_discoverable attributes // Set the adapter's name, is_powered and is_discoverable attributes
fn set_adapter(adapter: &BluetoothAdapter, adapter_name: String) -> Result<(), Box<Error>> { fn set_adapter(adapter: &BluetoothAdapter, adapter_name: String) -> Result<(), Box<Error>> {
try!(adapter.set_name(adapter_name)); adapter.set_name(adapter_name)?;
try!(adapter.set_powered(true)); adapter.set_powered(true)?;
try!(adapter.set_discoverable(true)); adapter.set_discoverable(true)?;
Ok(()) Ok(())
} }
@ -140,10 +140,10 @@ fn create_device(adapter: &BluetoothAdapter,
name: String, name: String,
address: String) address: String)
-> Result<BluetoothDevice, Box<Error>> { -> Result<BluetoothDevice, Box<Error>> {
let device = try!(BluetoothDevice::create_mock_device(adapter.clone(), generate_id().to_string())); let device = BluetoothDevice::create_mock_device(adapter.clone(), generate_id().to_string())?;
try!(device.set_name(Some(name))); device.set_name(Some(name))?;
try!(device.set_address(address)); device.set_address(address)?;
try!(device.set_connectable(true)); device.set_connectable(true)?;
Ok(device) Ok(device)
} }
@ -153,8 +153,8 @@ fn create_device_with_uuids(adapter: &BluetoothAdapter,
address: String, address: String,
uuids: Vec<String>) uuids: Vec<String>)
-> Result<BluetoothDevice, Box<Error>> { -> Result<BluetoothDevice, Box<Error>> {
let device = try!(create_device(adapter, name, address)); let device = create_device(adapter, name, address)?;
try!(device.set_uuids(uuids)); device.set_uuids(uuids)?;
Ok(device) Ok(device)
} }
@ -162,8 +162,8 @@ fn create_device_with_uuids(adapter: &BluetoothAdapter,
fn create_service(device: &BluetoothDevice, fn create_service(device: &BluetoothDevice,
uuid: String) uuid: String)
-> Result<BluetoothGATTService, Box<Error>> { -> Result<BluetoothGATTService, Box<Error>> {
let service = try!(BluetoothGATTService::create_mock_service(device.clone(), generate_id().to_string())); let service = BluetoothGATTService::create_mock_service(device.clone(), generate_id().to_string())?;
try!(service.set_uuid(uuid)); service.set_uuid(uuid)?;
Ok(service) Ok(service)
} }
@ -172,8 +172,8 @@ fn create_characteristic(service: &BluetoothGATTService,
uuid: String) uuid: String)
-> Result<BluetoothGATTCharacteristic, Box<Error>> { -> Result<BluetoothGATTCharacteristic, Box<Error>> {
let characteristic = let characteristic =
try!(BluetoothGATTCharacteristic::create_mock_characteristic(service.clone(), generate_id().to_string())); BluetoothGATTCharacteristic::create_mock_characteristic(service.clone(), generate_id().to_string())?;
try!(characteristic.set_uuid(uuid)); characteristic.set_uuid(uuid)?;
Ok(characteristic) Ok(characteristic)
} }
@ -182,8 +182,8 @@ fn create_characteristic_with_value(service: &BluetoothGATTService,
uuid: String, uuid: String,
value: Vec<u8>) value: Vec<u8>)
-> Result<BluetoothGATTCharacteristic, Box<Error>> { -> Result<BluetoothGATTCharacteristic, Box<Error>> {
let characteristic = try!(create_characteristic(service, uuid)); let characteristic = create_characteristic(service, uuid)?;
try!(characteristic.set_value(value)); characteristic.set_value(value)?;
Ok(characteristic) Ok(characteristic)
} }
@ -192,8 +192,8 @@ fn create_descriptor(characteristic: &BluetoothGATTCharacteristic,
uuid: String) uuid: String)
-> Result<BluetoothGATTDescriptor, Box<Error>> { -> Result<BluetoothGATTDescriptor, Box<Error>> {
let descriptor = let descriptor =
try!(BluetoothGATTDescriptor::create_mock_descriptor(characteristic.clone(), generate_id().to_string())); BluetoothGATTDescriptor::create_mock_descriptor(characteristic.clone(), generate_id().to_string())?;
try!(descriptor.set_uuid(uuid)); descriptor.set_uuid(uuid)?;
Ok(descriptor) Ok(descriptor)
} }
@ -202,8 +202,8 @@ fn create_descriptor_with_value(characteristic: &BluetoothGATTCharacteristic,
uuid: String, uuid: String,
value: Vec<u8>) value: Vec<u8>)
-> Result<BluetoothGATTDescriptor, Box<Error>> { -> Result<BluetoothGATTDescriptor, Box<Error>> {
let descriptor = try!(create_descriptor(characteristic, uuid)); let descriptor = create_descriptor(characteristic, uuid)?;
try!(descriptor.set_value(value)); descriptor.set_value(value)?;
Ok(descriptor) Ok(descriptor)
} }
@ -211,7 +211,7 @@ fn create_heart_rate_service(device: &BluetoothDevice,
empty: bool) empty: bool)
-> Result<BluetoothGATTService, Box<Error>> { -> Result<BluetoothGATTService, Box<Error>> {
// Heart Rate Service // Heart Rate Service
let heart_rate_service = try!(create_service(device, HEART_RATE_SERVICE_UUID.to_owned())); let heart_rate_service = create_service(device, HEART_RATE_SERVICE_UUID.to_owned())?;
if empty { if empty {
return Ok(heart_rate_service) return Ok(heart_rate_service)
@ -219,26 +219,26 @@ fn create_heart_rate_service(device: &BluetoothDevice,
// Heart Rate Measurement Characteristic // Heart Rate Measurement Characteristic
let heart_rate_measurement_characteristic = let heart_rate_measurement_characteristic =
try!(create_characteristic_with_value(&heart_rate_service, create_characteristic_with_value(&heart_rate_service,
HEART_RATE_MEASUREMENT_CHARACTERISTIC_UUID.to_owned(), HEART_RATE_MEASUREMENT_CHARACTERISTIC_UUID.to_owned(),
vec![0])); vec![0])?;
try!(heart_rate_measurement_characteristic.set_flags(vec![NOTIFY_FLAG.to_string(), heart_rate_measurement_characteristic.set_flags(vec![NOTIFY_FLAG.to_string(),
READ_FLAG.to_string(), READ_FLAG.to_string(),
WRITE_FLAG.to_string()])); WRITE_FLAG.to_string()])?;
// Body Sensor Location Characteristic 1 // Body Sensor Location Characteristic 1
let body_sensor_location_characteristic_1 = let body_sensor_location_characteristic_1 =
try!(create_characteristic_with_value(&heart_rate_service, create_characteristic_with_value(&heart_rate_service,
BODY_SENSOR_LOCATION_CHARACTERISTIC_UUID.to_owned(), BODY_SENSOR_LOCATION_CHARACTERISTIC_UUID.to_owned(),
vec![49])); vec![49])?;
try!(body_sensor_location_characteristic_1.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])); body_sensor_location_characteristic_1.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])?;
// Body Sensor Location Characteristic 2 // Body Sensor Location Characteristic 2
let body_sensor_location_characteristic_2 = let body_sensor_location_characteristic_2 =
try!(create_characteristic_with_value(&heart_rate_service, create_characteristic_with_value(&heart_rate_service,
BODY_SENSOR_LOCATION_CHARACTERISTIC_UUID.to_owned(), BODY_SENSOR_LOCATION_CHARACTERISTIC_UUID.to_owned(),
vec![50])); vec![50])?;
try!(body_sensor_location_characteristic_2.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])); body_sensor_location_characteristic_2.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])?;
Ok(heart_rate_service) Ok(heart_rate_service)
} }
@ -247,7 +247,7 @@ fn create_generic_access_service(device: &BluetoothDevice,
-> Result<BluetoothGATTService, Box<Error>> { -> Result<BluetoothGATTService, Box<Error>> {
// Generic Access Service // Generic Access Service
let generic_access_service = let generic_access_service =
try!(create_service(device, GENERIC_ACCESS_SERVICE_UUID.to_owned())); create_service(device, GENERIC_ACCESS_SERVICE_UUID.to_owned())?;
if empty { if empty {
return Ok(generic_access_service) return Ok(generic_access_service)
@ -255,41 +255,41 @@ fn create_generic_access_service(device: &BluetoothDevice,
// Device Name Characteristic // Device Name Characteristic
let device_name_characteristic = let device_name_characteristic =
try!(create_characteristic_with_value(&generic_access_service, create_characteristic_with_value(&generic_access_service,
DEVICE_NAME_CHARACTERISTIC_UUID.to_owned(), DEVICE_NAME_CHARACTERISTIC_UUID.to_owned(),
HEART_RATE_DEVICE_NAME.as_bytes().to_vec())); HEART_RATE_DEVICE_NAME.as_bytes().to_vec())?;
try!(device_name_characteristic.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])); device_name_characteristic.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])?;
// Number of Digitals descriptor // Number of Digitals descriptor
let number_of_digitals_descriptor_1 = let number_of_digitals_descriptor_1 =
try!(create_descriptor_with_value(&device_name_characteristic, create_descriptor_with_value(&device_name_characteristic,
NUMBER_OF_DIGITALS_UUID.to_owned(), NUMBER_OF_DIGITALS_UUID.to_owned(),
vec![49])); vec![49])?;
try!(number_of_digitals_descriptor_1.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])); number_of_digitals_descriptor_1.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])?;
let number_of_digitals_descriptor_2 = let number_of_digitals_descriptor_2 =
try!(create_descriptor_with_value(&device_name_characteristic, create_descriptor_with_value(&device_name_characteristic,
NUMBER_OF_DIGITALS_UUID.to_owned(), NUMBER_OF_DIGITALS_UUID.to_owned(),
vec![50])); vec![50])?;
try!(number_of_digitals_descriptor_2.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])); number_of_digitals_descriptor_2.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])?;
// Characteristic User Description Descriptor // Characteristic User Description Descriptor
let _characteristic_user_description = let _characteristic_user_description =
try!(create_descriptor_with_value(&device_name_characteristic, create_descriptor_with_value(&device_name_characteristic,
CHARACTERISTIC_USER_DESCRIPTION_UUID.to_owned(), CHARACTERISTIC_USER_DESCRIPTION_UUID.to_owned(),
HEART_RATE_DEVICE_NAME_DESCRIPTION.as_bytes().to_vec())); HEART_RATE_DEVICE_NAME_DESCRIPTION.as_bytes().to_vec())?;
// Client Characteristic Configuration descriptor // Client Characteristic Configuration descriptor
let _client_characteristic_configuration = let _client_characteristic_configuration =
try!(create_descriptor_with_value(&device_name_characteristic, create_descriptor_with_value(&device_name_characteristic,
CLIENT_CHARACTERISTIC_CONFIGURATION_UUID.to_owned(), CLIENT_CHARACTERISTIC_CONFIGURATION_UUID.to_owned(),
vec![0])); vec![0])?;
// Peripheral Privacy Flag Characteristic // Peripheral Privacy Flag Characteristic
let peripheral_privacy_flag_characteristic = let peripheral_privacy_flag_characteristic =
try!(create_characteristic(&generic_access_service, PERIPHERAL_PRIVACY_FLAG_CHARACTERISTIC_UUID.to_owned())); create_characteristic(&generic_access_service, PERIPHERAL_PRIVACY_FLAG_CHARACTERISTIC_UUID.to_owned())?;
try!(peripheral_privacy_flag_characteristic peripheral_privacy_flag_characteristic
.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])); .set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])?;
Ok(generic_access_service) Ok(generic_access_service)
} }
@ -299,149 +299,149 @@ fn create_heart_rate_device(adapter: &BluetoothAdapter,
-> Result<BluetoothDevice, Box<Error>> { -> Result<BluetoothDevice, Box<Error>> {
// Heart Rate Device // Heart Rate Device
let heart_rate_device = let heart_rate_device =
try!(create_device_with_uuids(adapter, create_device_with_uuids(adapter,
HEART_RATE_DEVICE_NAME.to_owned(), HEART_RATE_DEVICE_NAME.to_owned(),
HEART_RATE_DEVICE_ADDRESS.to_owned(), HEART_RATE_DEVICE_ADDRESS.to_owned(),
vec![GENERIC_ACCESS_SERVICE_UUID.to_owned(), vec![GENERIC_ACCESS_SERVICE_UUID.to_owned(),
HEART_RATE_SERVICE_UUID.to_owned()])); HEART_RATE_SERVICE_UUID.to_owned()])?;
if empty { if empty {
return Ok(heart_rate_device); return Ok(heart_rate_device);
} }
// Generic Access Service // Generic Access Service
let _generic_access_service = try!(create_generic_access_service(&heart_rate_device, false)); let _generic_access_service = create_generic_access_service(&heart_rate_device, false)?;
// Heart Rate Service // Heart Rate Service
let _heart_rate_service = try!(create_heart_rate_service(&heart_rate_device, false)); let _heart_rate_service = create_heart_rate_service(&heart_rate_device, false)?;
Ok(heart_rate_device) Ok(heart_rate_device)
} }
fn create_missing_characterisitc_heart_rate_device(adapter: &BluetoothAdapter) -> Result<(), Box<Error>> { fn create_missing_characterisitc_heart_rate_device(adapter: &BluetoothAdapter) -> Result<(), Box<Error>> {
let heart_rate_device_empty = try!(create_heart_rate_device(adapter, true)); let heart_rate_device_empty = create_heart_rate_device(adapter, true)?;
let _generic_access_service_empty = try!(create_generic_access_service(&heart_rate_device_empty, true)); let _generic_access_service_empty = create_generic_access_service(&heart_rate_device_empty, true)?;
let _heart_rate_service_empty = try!(create_heart_rate_service(&heart_rate_device_empty, true)); let _heart_rate_service_empty = create_heart_rate_service(&heart_rate_device_empty, true)?;
Ok(()) Ok(())
} }
fn create_missing_descriptor_heart_rate_device(adapter: &BluetoothAdapter) -> Result<(), Box<Error>> { fn create_missing_descriptor_heart_rate_device(adapter: &BluetoothAdapter) -> Result<(), Box<Error>> {
let heart_rate_device_empty = try!(create_heart_rate_device(adapter, true)); let heart_rate_device_empty = create_heart_rate_device(adapter, true)?;
let generic_access_service_empty = try!(create_generic_access_service(&heart_rate_device_empty, true)); let generic_access_service_empty = create_generic_access_service(&heart_rate_device_empty, true)?;
let _device_name_characteristic = let _device_name_characteristic =
try!(create_characteristic_with_value(&generic_access_service_empty, create_characteristic_with_value(&generic_access_service_empty,
DEVICE_NAME_CHARACTERISTIC_UUID.to_owned(), DEVICE_NAME_CHARACTERISTIC_UUID.to_owned(),
HEART_RATE_DEVICE_NAME.as_bytes().to_vec())); HEART_RATE_DEVICE_NAME.as_bytes().to_vec())?;
let peripheral_privacy_flag_characteristic = let peripheral_privacy_flag_characteristic =
try!(create_characteristic(&generic_access_service_empty, create_characteristic(&generic_access_service_empty,
PERIPHERAL_PRIVACY_FLAG_CHARACTERISTIC_UUID.to_owned())); PERIPHERAL_PRIVACY_FLAG_CHARACTERISTIC_UUID.to_owned())?;
try!(peripheral_privacy_flag_characteristic.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])); peripheral_privacy_flag_characteristic.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])?;
let _heart_rate_service = try!(create_heart_rate_service(&heart_rate_device_empty, false)); let _heart_rate_service = create_heart_rate_service(&heart_rate_device_empty, false)?;
Ok(()) Ok(())
} }
fn create_two_heart_rate_services_device(adapter: &BluetoothAdapter) -> Result<(), Box<Error>> { fn create_two_heart_rate_services_device(adapter: &BluetoothAdapter) -> Result<(), Box<Error>> {
let heart_rate_device_empty = try!(create_heart_rate_device(adapter, true)); let heart_rate_device_empty = create_heart_rate_device(adapter, true)?;
try!(heart_rate_device_empty.set_uuids(vec![GENERIC_ACCESS_SERVICE_UUID.to_owned(), heart_rate_device_empty.set_uuids(vec![GENERIC_ACCESS_SERVICE_UUID.to_owned(),
HEART_RATE_SERVICE_UUID.to_owned(), HEART_RATE_SERVICE_UUID.to_owned(),
HEART_RATE_SERVICE_UUID.to_owned()])); HEART_RATE_SERVICE_UUID.to_owned()])?;
let _generic_access_service = try!(create_generic_access_service(&heart_rate_device_empty, false)); let _generic_access_service = create_generic_access_service(&heart_rate_device_empty, false)?;
let heart_rate_service_empty_1 = try!(create_heart_rate_service(&heart_rate_device_empty, true)); let heart_rate_service_empty_1 = create_heart_rate_service(&heart_rate_device_empty, true)?;
let heart_rate_service_empty_2 = try!(create_heart_rate_service(&heart_rate_device_empty, true)); let heart_rate_service_empty_2 = create_heart_rate_service(&heart_rate_device_empty, true)?;
let heart_rate_measurement_characteristic = let heart_rate_measurement_characteristic =
try!(create_characteristic_with_value(&heart_rate_service_empty_1, create_characteristic_with_value(&heart_rate_service_empty_1,
HEART_RATE_MEASUREMENT_CHARACTERISTIC_UUID.to_owned(), HEART_RATE_MEASUREMENT_CHARACTERISTIC_UUID.to_owned(),
vec![0])); vec![0])?;
try!(heart_rate_measurement_characteristic.set_flags(vec![NOTIFY_FLAG.to_string()])); heart_rate_measurement_characteristic.set_flags(vec![NOTIFY_FLAG.to_string()])?;
let _body_sensor_location_characteristic_1 = let _body_sensor_location_characteristic_1 =
try!(create_characteristic_with_value(&heart_rate_service_empty_1, create_characteristic_with_value(&heart_rate_service_empty_1,
BODY_SENSOR_LOCATION_CHARACTERISTIC_UUID.to_owned(), BODY_SENSOR_LOCATION_CHARACTERISTIC_UUID.to_owned(),
vec![49])); vec![49])?;
let _body_sensor_location_characteristic_2 = let _body_sensor_location_characteristic_2 =
try!(create_characteristic_with_value(&heart_rate_service_empty_2, create_characteristic_with_value(&heart_rate_service_empty_2,
BODY_SENSOR_LOCATION_CHARACTERISTIC_UUID.to_owned(), BODY_SENSOR_LOCATION_CHARACTERISTIC_UUID.to_owned(),
vec![50])); vec![50])?;
Ok(()) Ok(())
} }
fn create_blocklisted_device(adapter: &BluetoothAdapter) -> Result<(), Box<Error>> { fn create_blocklisted_device(adapter: &BluetoothAdapter) -> Result<(), Box<Error>> {
let connectable_device = let connectable_device =
try!(create_device_with_uuids(adapter, create_device_with_uuids(adapter,
CONNECTABLE_DEVICE_NAME.to_owned(), CONNECTABLE_DEVICE_NAME.to_owned(),
CONNECTABLE_DEVICE_ADDRESS.to_owned(), CONNECTABLE_DEVICE_ADDRESS.to_owned(),
vec![BLOCKLIST_TEST_SERVICE_UUID.to_owned(), vec![BLOCKLIST_TEST_SERVICE_UUID.to_owned(),
DEVICE_INFORMATION_UUID.to_owned(), DEVICE_INFORMATION_UUID.to_owned(),
GENERIC_ACCESS_SERVICE_UUID.to_owned(), GENERIC_ACCESS_SERVICE_UUID.to_owned(),
HEART_RATE_SERVICE_UUID.to_owned(), HEART_RATE_SERVICE_UUID.to_owned(),
HUMAN_INTERFACE_DEVICE_SERVICE_UUID.to_owned()])); HUMAN_INTERFACE_DEVICE_SERVICE_UUID.to_owned()])?;
let blocklist_test_service = try!(create_service(&connectable_device, BLOCKLIST_TEST_SERVICE_UUID.to_owned())); let blocklist_test_service = create_service(&connectable_device, BLOCKLIST_TEST_SERVICE_UUID.to_owned())?;
let blocklist_exclude_reads_characteristic = let blocklist_exclude_reads_characteristic =
try!(create_characteristic(&blocklist_test_service, create_characteristic(&blocklist_test_service,
BLOCKLIST_EXCLUDE_READS_CHARACTERISTIC_UUID.to_owned())); BLOCKLIST_EXCLUDE_READS_CHARACTERISTIC_UUID.to_owned())?;
try!(blocklist_exclude_reads_characteristic blocklist_exclude_reads_characteristic
.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])); .set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])?;
let _blocklist_exclude_reads_descriptor = let _blocklist_exclude_reads_descriptor =
try!(create_descriptor_with_value(&blocklist_exclude_reads_characteristic, create_descriptor_with_value(&blocklist_exclude_reads_characteristic,
BLOCKLIST_EXCLUDE_READS_DESCRIPTOR_UUID.to_owned(), BLOCKLIST_EXCLUDE_READS_DESCRIPTOR_UUID.to_owned(),
vec![54; 3])); vec![54; 3])?;
let _blocklist_descriptor = let _blocklist_descriptor =
try!(create_descriptor_with_value(&blocklist_exclude_reads_characteristic, create_descriptor_with_value(&blocklist_exclude_reads_characteristic,
BLOCKLIST_DESCRIPTOR_UUID.to_owned(), BLOCKLIST_DESCRIPTOR_UUID.to_owned(),
vec![54; 3])); vec![54; 3])?;
let device_information_service = try!(create_service(&connectable_device, DEVICE_INFORMATION_UUID.to_owned())); let device_information_service = create_service(&connectable_device, DEVICE_INFORMATION_UUID.to_owned())?;
let _serial_number_string_characteristic = let _serial_number_string_characteristic =
try!(create_characteristic(&device_information_service, SERIAL_NUMBER_STRING_UUID.to_owned())); create_characteristic(&device_information_service, SERIAL_NUMBER_STRING_UUID.to_owned())?;
let _generic_access_service = try!(create_generic_access_service(&connectable_device, false)); let _generic_access_service = create_generic_access_service(&connectable_device, false)?;
let _heart_rate_service = try!(create_heart_rate_service(&connectable_device, false)); let _heart_rate_service = create_heart_rate_service(&connectable_device, false)?;
let _human_interface_device_service = let _human_interface_device_service =
try!(create_service(&connectable_device, HUMAN_INTERFACE_DEVICE_SERVICE_UUID.to_owned())); create_service(&connectable_device, HUMAN_INTERFACE_DEVICE_SERVICE_UUID.to_owned())?;
Ok(()) Ok(())
} }
fn create_glucose_heart_rate_devices(adapter: &BluetoothAdapter) -> Result<(), Box<Error>> { fn create_glucose_heart_rate_devices(adapter: &BluetoothAdapter) -> Result<(), Box<Error>> {
let glucose_devie = try!(create_device_with_uuids(adapter, let glucose_devie = create_device_with_uuids(adapter,
GLUCOSE_DEVICE_NAME.to_owned(), GLUCOSE_DEVICE_NAME.to_owned(),
GLUCOSE_DEVICE_ADDRESS.to_owned(), GLUCOSE_DEVICE_ADDRESS.to_owned(),
vec![GLUCOSE_SERVICE_UUID.to_owned(), vec![GLUCOSE_SERVICE_UUID.to_owned(),
TX_POWER_SERVICE_UUID.to_owned()])); TX_POWER_SERVICE_UUID.to_owned()])?;
let heart_rate_device_empty = try!(create_heart_rate_device(adapter, true)); let heart_rate_device_empty = create_heart_rate_device(adapter, true)?;
let mut manufacturer_dta = HashMap::new(); let mut manufacturer_dta = HashMap::new();
manufacturer_dta.insert(17, vec![1, 2, 3]); manufacturer_dta.insert(17, vec![1, 2, 3]);
try!(glucose_devie.set_manufacturer_data(manufacturer_dta)); glucose_devie.set_manufacturer_data(manufacturer_dta)?;
let mut service_data = HashMap::new(); let mut service_data = HashMap::new();
service_data.insert(GLUCOSE_SERVICE_UUID.to_owned(), vec![1, 2, 3]); service_data.insert(GLUCOSE_SERVICE_UUID.to_owned(), vec![1, 2, 3]);
try!(glucose_devie.set_service_data(service_data)); glucose_devie.set_service_data(service_data)?;
service_data = HashMap::new(); service_data = HashMap::new();
service_data.insert(HEART_RATE_SERVICE_UUID.to_owned(), vec![1, 2, 3]); service_data.insert(HEART_RATE_SERVICE_UUID.to_owned(), vec![1, 2, 3]);
try!(heart_rate_device_empty.set_service_data(service_data)); heart_rate_device_empty.set_service_data(service_data)?;
Ok(()) Ok(())
} }
@ -453,68 +453,68 @@ pub fn test(manager: &mut BluetoothManager, data_set_name: String) -> Result<(),
}; };
match data_set_name.as_str() { match data_set_name.as_str() {
NOT_PRESENT_ADAPTER => { NOT_PRESENT_ADAPTER => {
try!(set_adapter(adapter, NOT_PRESENT_ADAPTER.to_owned())); set_adapter(adapter, NOT_PRESENT_ADAPTER.to_owned())?;
try!(adapter.set_present(false)); adapter.set_present(false)?;
}, },
NOT_POWERED_ADAPTER => { NOT_POWERED_ADAPTER => {
try!(set_adapter(adapter, NOT_POWERED_ADAPTER.to_owned())); set_adapter(adapter, NOT_POWERED_ADAPTER.to_owned())?;
try!(adapter.set_powered(false)); adapter.set_powered(false)?;
}, },
EMPTY_ADAPTER => { EMPTY_ADAPTER => {
try!(set_adapter(adapter, EMPTY_ADAPTER.to_owned())); set_adapter(adapter, EMPTY_ADAPTER.to_owned())?;
}, },
GLUCOSE_HEART_RATE_ADAPTER => { GLUCOSE_HEART_RATE_ADAPTER => {
try!(set_adapter(adapter, GLUCOSE_HEART_RATE_ADAPTER.to_owned())); set_adapter(adapter, GLUCOSE_HEART_RATE_ADAPTER.to_owned())?;
let _ = try!(create_glucose_heart_rate_devices(adapter)); let _ = create_glucose_heart_rate_devices(adapter)?;
}, },
UNICODE_DEVICE_ADAPTER => { UNICODE_DEVICE_ADAPTER => {
try!(set_adapter(adapter, UNICODE_DEVICE_ADAPTER.to_owned())); set_adapter(adapter, UNICODE_DEVICE_ADAPTER.to_owned())?;
let _unicode_device = try!(create_device(adapter, let _unicode_device = create_device(adapter,
UNICODE_DEVICE_NAME.to_owned(), UNICODE_DEVICE_NAME.to_owned(),
UNICODE_DEVICE_ADDRESS.to_owned())); UNICODE_DEVICE_ADDRESS.to_owned())?;
}, },
MISSING_SERVICE_HEART_RATE_ADAPTER => { MISSING_SERVICE_HEART_RATE_ADAPTER => {
try!(set_adapter(adapter, MISSING_SERVICE_HEART_RATE_ADAPTER.to_owned())); set_adapter(adapter, MISSING_SERVICE_HEART_RATE_ADAPTER.to_owned())?;
let _heart_rate_device_empty = try!(create_heart_rate_device(adapter, true)); let _heart_rate_device_empty = create_heart_rate_device(adapter, true)?;
}, },
MISSING_CHARACTERISTIC_HEART_RATE_ADAPTER => { MISSING_CHARACTERISTIC_HEART_RATE_ADAPTER => {
try!(set_adapter(adapter, MISSING_CHARACTERISTIC_HEART_RATE_ADAPTER.to_owned())); set_adapter(adapter, MISSING_CHARACTERISTIC_HEART_RATE_ADAPTER.to_owned())?;
let _ = try!(create_missing_characterisitc_heart_rate_device(adapter)); let _ = create_missing_characterisitc_heart_rate_device(adapter)?;
}, },
MISSING_DESCRIPTOR_HEART_RATE_ADAPTER => { MISSING_DESCRIPTOR_HEART_RATE_ADAPTER => {
try!(set_adapter(adapter, MISSING_DESCRIPTOR_HEART_RATE_ADAPTER.to_owned())); set_adapter(adapter, MISSING_DESCRIPTOR_HEART_RATE_ADAPTER.to_owned())?;
let _ = try!(create_missing_descriptor_heart_rate_device(adapter)); let _ = create_missing_descriptor_heart_rate_device(adapter)?;
}, },
HEART_RATE_ADAPTER => { HEART_RATE_ADAPTER => {
try!(set_adapter(adapter, HEART_RATE_ADAPTER.to_owned())); set_adapter(adapter, HEART_RATE_ADAPTER.to_owned())?;
let _heart_rate_device = try!(create_heart_rate_device(adapter, false)); let _heart_rate_device = create_heart_rate_device(adapter, false)?;
}, },
EMPTY_NAME_HEART_RATE_ADAPTER => { EMPTY_NAME_HEART_RATE_ADAPTER => {
try!(set_adapter(adapter, EMPTY_NAME_HEART_RATE_ADAPTER.to_owned())); set_adapter(adapter, EMPTY_NAME_HEART_RATE_ADAPTER.to_owned())?;
let heart_rate_device = try!(create_heart_rate_device(adapter, false)); let heart_rate_device = create_heart_rate_device(adapter, false)?;
try!(heart_rate_device.set_name(Some(EMPTY_DEVICE_NAME.to_owned()))); heart_rate_device.set_name(Some(EMPTY_DEVICE_NAME.to_owned()))?;
}, },
NO_NAME_HEART_RATE_ADAPTER => { NO_NAME_HEART_RATE_ADAPTER => {
try!(set_adapter(adapter, NO_NAME_HEART_RATE_ADAPTER.to_owned())); set_adapter(adapter, NO_NAME_HEART_RATE_ADAPTER.to_owned())?;
let heart_rate_device = try!(create_heart_rate_device(adapter, false)); let heart_rate_device = create_heart_rate_device(adapter, false)?;
try!(heart_rate_device.set_name(None)); heart_rate_device.set_name(None)?;
}, },
TWO_HEART_RATE_SERVICES_ADAPTER => { TWO_HEART_RATE_SERVICES_ADAPTER => {
try!(set_adapter(adapter, TWO_HEART_RATE_SERVICES_ADAPTER.to_owned())); set_adapter(adapter, TWO_HEART_RATE_SERVICES_ADAPTER.to_owned())?;
let _ = try!(create_two_heart_rate_services_device(adapter)); let _ = create_two_heart_rate_services_device(adapter)?;
}, },
BLOCKLIST_TEST_ADAPTER => { BLOCKLIST_TEST_ADAPTER => {
try!(set_adapter(adapter, BLOCKLIST_TEST_ADAPTER.to_owned())); set_adapter(adapter, BLOCKLIST_TEST_ADAPTER.to_owned())?;
let _ = try!(create_blocklisted_device(adapter)); let _ = create_blocklisted_device(adapter)?;
}, },
_ => return Err(Box::from(WRONG_DATA_SET_ERROR.to_string())), _ => return Err(Box::from(WRONG_DATA_SET_ERROR.to_string())),
} }

View file

@ -56,11 +56,11 @@ impl GLContextWrapper {
fn resize(&mut self, size: Size2D<i32>) -> Result<Size2D<i32>, &'static str> { fn resize(&mut self, size: Size2D<i32>) -> Result<Size2D<i32>, &'static str> {
match *self { match *self {
GLContextWrapper::Native(ref mut ctx) => { GLContextWrapper::Native(ref mut ctx) => {
try!(ctx.resize(size)); ctx.resize(size)?;
Ok(ctx.borrow_draw_buffer().unwrap().size()) Ok(ctx.borrow_draw_buffer().unwrap().size())
} }
GLContextWrapper::OSMesa(ref mut ctx) => { GLContextWrapper::OSMesa(ref mut ctx) => {
try!(ctx.resize(size)); ctx.resize(size)?;
Ok(ctx.borrow_draw_buffer().unwrap().size()) Ok(ctx.borrow_draw_buffer().unwrap().size())
} }
} }
@ -115,7 +115,7 @@ fn create_readback_painter(size: Size2D<i32>,
webrender_api: webrender_traits::RenderApi, webrender_api: webrender_traits::RenderApi,
gl_type: gl::GlType) gl_type: gl::GlType)
-> Result<(WebGLPaintThread, GLLimits), String> { -> Result<(WebGLPaintThread, GLLimits), String> {
let context = try!(GLContextWrapper::new(size, attrs, gl_type)); let context = GLContextWrapper::new(size, attrs, gl_type)?;
let limits = context.get_limits(); let limits = context.get_limits();
let painter = WebGLPaintThread { let painter = WebGLPaintThread {
size: size, size: size,
@ -294,7 +294,7 @@ impl WebGLPaintThread {
WebGLPaintTaskData::Readback(ref mut context, ref webrender_api, ref mut image_key) => { WebGLPaintTaskData::Readback(ref mut context, ref webrender_api, ref mut image_key) => {
if size.width > self.size.width || if size.width > self.size.width ||
size.height > self.size.height { size.height > self.size.height {
self.size = try!(context.resize(size)); self.size = context.resize(size)?;
} else { } else {
self.size = size; self.size = size;
context.gl().scissor(0, 0, size.width, size.height); context.gl().scissor(0, 0, size.width, size.height);

View file

@ -113,7 +113,7 @@ impl Pref {
} }
fn from_json(data: Json) -> Result<Pref, ()> { fn from_json(data: Json) -> Result<Pref, ()> {
let value = try!(PrefValue::from_json(data)); let value = PrefValue::from_json(data)?;
Ok(Pref::new_default(value)) Ok(Pref::new_default(value))
} }
@ -158,10 +158,10 @@ pub fn default_prefs() -> Preferences {
pub fn read_prefs_from_file<T>(mut file: T) pub fn read_prefs_from_file<T>(mut file: T)
-> Result<HashMap<String, Pref>, ()> where T: Read { -> Result<HashMap<String, Pref>, ()> where T: Read {
let json = try!(Json::from_reader(&mut file).or_else(|e| { let json = Json::from_reader(&mut file).or_else(|e| {
println!("Ignoring invalid JSON in preferences: {:?}.", e); println!("Ignoring invalid JSON in preferences: {:?}.", e);
Err(()) Err(())
})); })?;
let mut prefs = HashMap::new(); let mut prefs = HashMap::new();
if let Json::Object(obj) = json { if let Json::Object(obj) = json {
@ -205,14 +205,14 @@ fn init_user_prefs(path: &mut PathBuf) {
} }
fn read_prefs() -> Result<HashMap<String, Pref>, ()> { fn read_prefs() -> Result<HashMap<String, Pref>, ()> {
let mut path = try!(resources_dir_path().map_err(|_| ())); let mut path = resources_dir_path().map_err(|_| ())?;
path.push("prefs.json"); path.push("prefs.json");
let file = try!(File::open(path).or_else(|e| { let file = File::open(path).or_else(|e| {
writeln!(&mut stderr(), "Error opening preferences: {:?}.", e) writeln!(&mut stderr(), "Error opening preferences: {:?}.", e)
.expect("failed printing to stderr"); .expect("failed printing to stderr");
Err(()) Err(())
})); })?;
read_prefs_from_file(file) read_prefs_from_file(file)
} }

View file

@ -44,9 +44,9 @@ pub fn resources_dir_path() -> io::Result<PathBuf> {
// FIXME: Find a way to not rely on the executable being // FIXME: Find a way to not rely on the executable being
// under `<servo source>[/$target_triple]/target/debug` // under `<servo source>[/$target_triple]/target/debug`
// or `<servo source>[/$target_triple]/target/release`. // or `<servo source>[/$target_triple]/target/release`.
let mut path = try!(env::current_exe()); let mut path = env::current_exe()?;
// Follow symlink // Follow symlink
path = try!(path.canonicalize()); path = path.canonicalize()?;
while path.pop() { while path.pop() {
path.push("resources"); path.push("resources");
@ -66,10 +66,10 @@ pub fn resources_dir_path() -> io::Result<PathBuf> {
} }
pub fn read_resource_file<P: AsRef<Path>>(relative_path: P) -> io::Result<Vec<u8>> { pub fn read_resource_file<P: AsRef<Path>>(relative_path: P) -> io::Result<Vec<u8>> {
let mut path = try!(resources_dir_path()); let mut path = resources_dir_path()?;
path.push(relative_path); path.push(relative_path);
let mut file = try!(File::open(&path)); let mut file = File::open(&path)?;
let mut data = Vec::new(); let mut data = Vec::new();
try!(file.read_to_end(&mut data)); file.read_to_end(&mut data)?;
Ok(data) Ok(data)
} }

View file

@ -273,7 +273,7 @@ impl Pipeline {
// //
// Yes, that's all there is to it! // Yes, that's all there is to it!
if opts::multiprocess() { if opts::multiprocess() {
let _ = try!(unprivileged_pipeline_content.spawn_multiprocess()); let _ = unprivileged_pipeline_content.spawn_multiprocess()?;
} else { } else {
unprivileged_pipeline_content.start_all::<Message, LTF, STF>(false); unprivileged_pipeline_content.start_all::<Message, LTF, STF>(false);
} }
@ -563,7 +563,7 @@ impl UnprivilegedPipelineContent {
} }
let (_receiver, sender) = server.accept().expect("Server failed to accept."); let (_receiver, sender) = server.accept().expect("Server failed to accept.");
try!(sender.send(self)); sender.send(self)?;
Ok(()) Ok(())
} }

View file

@ -159,7 +159,7 @@ impl ActorRegistry {
None => debug!("message received for unknown actor \"{}\"", to), None => debug!("message received for unknown actor \"{}\"", to),
Some(actor) => { Some(actor) => {
let msg_type = msg.get("type").unwrap().as_str().unwrap(); let msg_type = msg.get("type").unwrap().as_str().unwrap();
if try!(actor.handle_message(self, msg_type, msg, stream)) if actor.handle_message(self, msg_type, msg, stream)?
!= ActorMessageStatus::Processed { != ActorMessageStatus::Processed {
debug!("unexpected message type \"{}\" found for actor \"{}\"", debug!("unexpected message type \"{}\" found for actor \"{}\"",
msg_type, to); msg_type, to);

View file

@ -115,7 +115,7 @@ impl Actor for ConsoleActor {
let (chan, port) = ipc::channel().unwrap(); let (chan, port) = ipc::channel().unwrap();
self.script_chan.send(DevtoolScriptControlMsg::GetCachedMessages( self.script_chan.send(DevtoolScriptControlMsg::GetCachedMessages(
self.pipeline, message_types, chan)).unwrap(); self.pipeline, message_types, chan)).unwrap();
let messages = try!(port.recv().map_err(|_| ())).into_iter().map(|message| { let messages = port.recv().map_err(|_| ())?.into_iter().map(|message| {
let json_string = message.encode().unwrap(); let json_string = message.encode().unwrap();
let json = serde_json::from_str::<Value>(&json_string).unwrap(); let json = serde_json::from_str::<Value>(&json_string).unwrap();
json.as_object().unwrap().to_owned() json.as_object().unwrap().to_owned()
@ -179,7 +179,7 @@ impl Actor for ConsoleActor {
self.pipeline, input.clone(), chan)).unwrap(); self.pipeline, input.clone(), chan)).unwrap();
//TODO: extract conversion into protocol module or some other useful place //TODO: extract conversion into protocol module or some other useful place
let result = match try!(port.recv().map_err(|_| ())) { let result = match port.recv().map_err(|_| ())? {
VoidValue => { VoidValue => {
let mut m = Map::new(); let mut m = Map::new();
m.insert("type".to_owned(), Value::String("undefined".to_owned())); m.insert("type".to_owned(), Value::String("undefined".to_owned()));

View file

@ -289,7 +289,7 @@ impl Actor for WalkerActor {
"documentElement" => { "documentElement" => {
let (tx, rx) = ipc::channel().unwrap(); let (tx, rx) = ipc::channel().unwrap();
self.script_chan.send(GetDocumentElement(self.pipeline, tx)).unwrap(); self.script_chan.send(GetDocumentElement(self.pipeline, tx)).unwrap();
let doc_elem_info = try!(rx.recv().unwrap().ok_or(())); let doc_elem_info = rx.recv().unwrap().ok_or(())?;
let node = doc_elem_info.encode(registry, true, self.script_chan.clone(), self.pipeline); let node = doc_elem_info.encode(registry, true, self.script_chan.clone(), self.pipeline);
let msg = DocumentElementReply { let msg = DocumentElementReply {
@ -315,7 +315,7 @@ impl Actor for WalkerActor {
registry.actor_to_script(target.to_owned()), registry.actor_to_script(target.to_owned()),
tx)) tx))
.unwrap(); .unwrap();
let children = try!(rx.recv().unwrap().ok_or(())); let children = rx.recv().unwrap().ok_or(())?;
let msg = ChildrenReply { let msg = ChildrenReply {
hasFirst: true, hasFirst: true,
@ -489,7 +489,7 @@ impl Actor for PageStyleActor {
borderTopWidth, borderRightWidth, borderBottomWidth, borderLeftWidth, borderTopWidth, borderRightWidth, borderBottomWidth, borderLeftWidth,
paddingTop, paddingRight, paddingBottom, paddingLeft, paddingTop, paddingRight, paddingBottom, paddingLeft,
width, height, width, height,
} = try!(rx.recv().unwrap().ok_or(())); } = rx.recv().unwrap().ok_or(())?;
let auto_margins = msg.get("autoMargins") let auto_margins = msg.get("autoMargins")
.and_then(&Value::as_bool).unwrap_or(false); .and_then(&Value::as_bool).unwrap_or(false);
@ -563,7 +563,7 @@ impl Actor for InspectorActor {
let (tx, rx) = ipc::channel().unwrap(); let (tx, rx) = ipc::channel().unwrap();
self.script_chan.send(GetRootNode(self.pipeline, tx)).unwrap(); self.script_chan.send(GetRootNode(self.pipeline, tx)).unwrap();
let root_info = try!(rx.recv().unwrap().ok_or(())); let root_info = rx.recv().unwrap().ok_or(())?;
let node = root_info.encode(registry, false, self.script_chan.clone(), self.pipeline); let node = root_info.encode(registry, false, self.script_chan.clone(), self.pipeline);

View file

@ -88,9 +88,9 @@ impl FontContext {
font_variant_caps::T::normal => pt_size, font_variant_caps::T::normal => pt_size,
}; };
let handle = try!(FontHandle::new_from_template(&self.platform_handle, let handle = FontHandle::new_from_template(&self.platform_handle,
template, template,
Some(actual_pt_size))); Some(actual_pt_size))?;
Ok(Font::new(handle, variant, descriptor, pt_size, actual_pt_size, font_key)) Ok(Font::new(handle, variant, descriptor, pt_size, actual_pt_size, font_key))
} }

View file

@ -80,7 +80,7 @@ impl Debug for FontTemplate {
impl FontTemplate { impl FontTemplate {
pub fn new(identifier: Atom, maybe_bytes: Option<Vec<u8>>) -> Result<FontTemplate, IoError> { pub fn new(identifier: Atom, maybe_bytes: Option<Vec<u8>>) -> Result<FontTemplate, IoError> {
let maybe_data = match maybe_bytes { let maybe_data = match maybe_bytes {
Some(_) => Some(try!(FontTemplateData::new(identifier.clone(), maybe_bytes))), Some(_) => Some(FontTemplateData::new(identifier.clone(), maybe_bytes)?),
None => None, None => None,
}; };
@ -167,12 +167,12 @@ impl FontTemplate {
return Err(()) return Err(())
} }
let data = try!(self.data().map_err(|_| ())); let data = self.data().map_err(|_| ())?;
let handle: Result<FontHandle, ()> = FontHandleMethods::new_from_template(font_context, let handle: Result<FontHandle, ()> = FontHandleMethods::new_from_template(font_context,
data, data,
None); None);
self.is_valid = handle.is_ok(); self.is_valid = handle.is_ok();
let handle = try!(handle); let handle = handle?;
self.descriptor = Some(FontTemplateDescriptor::new(handle.boldness(), self.descriptor = Some(FontTemplateDescriptor::new(handle.boldness(),
handle.stretchiness(), handle.stretchiness(),
handle.is_italic())); handle.is_italic()));
@ -202,7 +202,7 @@ impl FontTemplate {
} }
assert!(self.strong_ref.is_none()); assert!(self.strong_ref.is_none());
let template_data = Arc::new(try!(FontTemplateData::new(self.identifier.clone(), None))); let template_data = Arc::new(FontTemplateData::new(self.identifier.clone(), None)?);
self.weak_ref = Some(Arc::downgrade(&template_data)); self.weak_ref = Some(Arc::downgrade(&template_data));
Ok(template_data) Ok(template_data)
} }

View file

@ -235,9 +235,9 @@ impl FontList {
fn load_file(path: &str) -> Result<String, io::Error> { fn load_file(path: &str) -> Result<String, io::Error> {
let mut file = try!(File::open(path)); let mut file = File::open(path)?;
let mut content = String::new(); let mut content = String::new();
try!(file.read_to_string(&mut content)); file.read_to_string(&mut content)?;
Ok(content) Ok(content)
} }

View file

@ -99,7 +99,7 @@ impl FontHandleMethods for FontHandle {
return Err(()); return Err(());
} }
if let Some(s) = pt_size { if let Some(s) = pt_size {
try!(FontHandle::set_char_size(face, s).or(Err(()))) FontHandle::set_char_size(face, s).or(Err(()))?
} }
Ok(face) Ok(face)
} }

View file

@ -25,7 +25,7 @@ impl FontTemplateData {
}, },
None => { None => {
// TODO: Handle file load failure! // TODO: Handle file load failure!
let mut file = try!(File::open(&*identifier)); let mut file = File::open(&*identifier)?;
let mut buffer = vec![]; let mut buffer = vec![];
file.read_to_end(&mut buffer).unwrap(); file.read_to_end(&mut buffer).unwrap();
buffer buffer

View file

@ -47,7 +47,7 @@ fn make_tag(tag_bytes: &[u8]) -> FontTableTag {
unsafe { *(tag_bytes.as_ptr() as *const FontTableTag) } unsafe { *(tag_bytes.as_ptr() as *const FontTableTag) }
} }
macro_rules! try_lossy(($result:expr) => (try!($result.map_err(|_| (()))))); macro_rules! try_lossy(($result:expr) => ($result.map_err(|_| (()))?));
// Given a set of records, figure out the string indices for the family and face // Given a set of records, figure out the string indices for the family and face
// names. We want name_id 1 and 2, and we need to use platform_id == 1 and // names. We want name_id 1 and 2, and we need to use platform_id == 1 and
@ -262,12 +262,12 @@ impl FontHandleMethods for FontHandle {
} }
let face = font_file.unwrap().create_face(0, dwrote::DWRITE_FONT_SIMULATIONS_NONE); let face = font_file.unwrap().create_face(0, dwrote::DWRITE_FONT_SIMULATIONS_NONE);
let info = try!(FontInfo::new_from_face(&face)); let info = FontInfo::new_from_face(&face)?;
(info, face) (info, face)
} else { } else {
let font = font_from_atom(&template.identifier); let font = font_from_atom(&template.identifier);
let face = font.create_font_face(); let face = font.create_font_face();
let info = try!(FontInfo::new_from_font(&font)); let info = FontInfo::new_from_font(&font)?;
(info, face) (info, face)
}; };

View file

@ -665,27 +665,27 @@ impl<'a> GlyphStore {
impl fmt::Debug for GlyphStore { impl fmt::Debug for GlyphStore {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
try!(write!(formatter, "GlyphStore:\n")); write!(formatter, "GlyphStore:\n")?;
let mut detailed_buffer = self.detail_store.detail_buffer.iter(); let mut detailed_buffer = self.detail_store.detail_buffer.iter();
for entry in self.entry_buffer.iter() { for entry in self.entry_buffer.iter() {
if entry.is_simple() { if entry.is_simple() {
try!(write!(formatter, write!(formatter,
" simple id={:?} advance={:?}\n", " simple id={:?} advance={:?}\n",
entry.id(), entry.id(),
entry.advance())); entry.advance())?;
continue continue
} }
if entry.is_initial() { if entry.is_initial() {
continue continue
} }
try!(write!(formatter, " complex...")); write!(formatter, " complex...")?;
if detailed_buffer.next().is_none() { if detailed_buffer.next().is_none() {
continue continue
} }
try!(write!(formatter, write!(formatter,
" detailed id={:?} advance={:?}\n", " detailed id={:?} advance={:?}\n",
entry.id(), entry.id(),
entry.advance())); entry.advance())?;
} }
Ok(()) Ok(())
} }

View file

@ -78,9 +78,9 @@ impl FloatList {
impl fmt::Debug for FloatList { impl fmt::Debug for FloatList {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "max_block_start={:?} floats={}", self.max_block_start, self.floats.len())); write!(f, "max_block_start={:?} floats={}", self.max_block_start, self.floats.len())?;
for float in self.floats.iter() { for float in self.floats.iter() {
try!(write!(f, " {:?}", float)); write!(f, " {:?}", float)?;
} }
Ok(()) Ok(())
} }

View file

@ -1011,14 +1011,12 @@ impl fmt::Debug for BaseFlow {
impl Serialize for BaseFlow { impl Serialize for BaseFlow {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut serializer = try!(serializer.serialize_struct("base", 5)); let mut serializer = serializer.serialize_struct("base", 5)?;
try!(serializer.serialize_field("id", &self.debug_id())); serializer.serialize_field("id", &self.debug_id())?;
try!(serializer.serialize_field("stacking_relative_position", serializer.serialize_field("stacking_relative_position", &self.stacking_relative_position)?;
&self.stacking_relative_position)); serializer.serialize_field("intrinsic_inline_sizes", &self.intrinsic_inline_sizes)?;
try!(serializer.serialize_field("intrinsic_inline_sizes", serializer.serialize_field("position", &self.position)?;
&self.intrinsic_inline_sizes)); serializer.serialize_field("children", &self.children)?;
try!(serializer.serialize_field("position", &self.position));
try!(serializer.serialize_field("children", &self.children));
serializer.end() serializer.end()
} }
} }

View file

@ -24,7 +24,7 @@ pub struct FlowList {
impl Serialize for FlowList { impl Serialize for FlowList {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut serializer = try!(serializer.serialize_seq(Some(self.len()))); let mut serializer = serializer.serialize_seq(Some(self.len()))?;
for f in self.iter() { for f in self.iter() {
let mut flow_val = Map::new(); let mut flow_val = Map::new();
flow_val.insert("class".to_owned(), to_value(f.class()).unwrap()); flow_val.insert("class".to_owned(), to_value(f.class()).unwrap());
@ -43,7 +43,7 @@ impl Serialize for FlowList {
} }
}; };
flow_val.insert("data".to_owned(), data); flow_val.insert("data".to_owned(), data);
try!(serializer.serialize_element(&flow_val)); serializer.serialize_element(&flow_val)?;
} }
serializer.end() serializer.end()
} }

View file

@ -143,10 +143,10 @@ pub struct Fragment {
impl Serialize for Fragment { impl Serialize for Fragment {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut serializer = try!(serializer.serialize_struct("fragment", 3)); let mut serializer = serializer.serialize_struct("fragment", 3)?;
try!(serializer.serialize_field("id", &self.debug_id)); serializer.serialize_field("id", &self.debug_id)?;
try!(serializer.serialize_field("border_box", &self.border_box)); serializer.serialize_field("border_box", &self.border_box)?;
try!(serializer.serialize_field("margin", &self.margin)); serializer.serialize_field("margin", &self.margin)?;
serializer.end() serializer.end()
} }
} }

View file

@ -1662,7 +1662,7 @@ fn get_root_flow_background_color(flow: &mut Flow) -> webrender_traits::ColorF {
fn get_ua_stylesheets() -> Result<UserAgentStylesheets, &'static str> { fn get_ua_stylesheets() -> Result<UserAgentStylesheets, &'static str> {
fn parse_ua_stylesheet(shared_lock: &SharedRwLock, filename: &'static str) fn parse_ua_stylesheet(shared_lock: &SharedRwLock, filename: &'static str)
-> Result<Stylesheet, &'static str> { -> Result<Stylesheet, &'static str> {
let res = try!(read_resource_file(filename).map_err(|_| filename)); let res = read_resource_file(filename).map_err(|_| filename)?;
Ok(Stylesheet::from_bytes( Ok(Stylesheet::from_bytes(
&res, &res,
ServoUrl::parse(&format!("chrome://resources/{:?}", filename)).unwrap(), ServoUrl::parse(&format!("chrome://resources/{:?}", filename)).unwrap(),
@ -1681,7 +1681,7 @@ fn get_ua_stylesheets() -> Result<UserAgentStylesheets, &'static str> {
// FIXME: presentational-hints.css should be at author origin with zero specificity. // FIXME: presentational-hints.css should be at author origin with zero specificity.
// (Does it make a difference?) // (Does it make a difference?)
for &filename in &["user-agent.css", "servo.css", "presentational-hints.css"] { for &filename in &["user-agent.css", "servo.css", "presentational-hints.css"] {
user_or_user_agent_stylesheets.push(try!(parse_ua_stylesheet(&shared_lock, filename))); user_or_user_agent_stylesheets.push(parse_ua_stylesheet(&shared_lock, filename)?);
} }
for &(ref contents, ref url) in &opts::get().user_stylesheets { for &(ref contents, ref url) in &opts::get().user_stylesheets {
user_or_user_agent_stylesheets.push(Stylesheet::from_bytes( user_or_user_agent_stylesheets.push(Stylesheet::from_bytes(
@ -1689,7 +1689,7 @@ fn get_ua_stylesheets() -> Result<UserAgentStylesheets, &'static str> {
shared_lock.clone(), None, &RustLogReporter, QuirksMode::NoQuirks)); shared_lock.clone(), None, &RustLogReporter, QuirksMode::NoQuirks));
} }
let quirks_mode_stylesheet = try!(parse_ua_stylesheet(&shared_lock, "quirks-mode.css")); let quirks_mode_stylesheet = parse_ua_stylesheet(&shared_lock, "quirks-mode.css")?;
Ok(UserAgentStylesheets { Ok(UserAgentStylesheets {
shared_lock: shared_lock, shared_lock: shared_lock,

View file

@ -36,7 +36,7 @@ impl NetworkConnector for HttpsConnector {
// Perform host replacement when making the actual TCP connection. // Perform host replacement when making the actual TCP connection.
let addr = &(&*replace_host(host), port); let addr = &(&*replace_host(host), port);
let stream = HttpStream(try!(TcpStream::connect(addr))); let stream = HttpStream(TcpStream::connect(addr)?);
if scheme == "http" { if scheme == "http" {
Ok(HttpsStream::Http(stream)) Ok(HttpsStream::Http(stream))

View file

@ -357,14 +357,14 @@ impl FileManagerStore {
fn create_entry(&self, file_path: &Path, origin: &str) -> Result<SelectedFile, FileManagerThreadError> { fn create_entry(&self, file_path: &Path, origin: &str) -> Result<SelectedFile, FileManagerThreadError> {
use net_traits::filemanager_thread::FileManagerThreadError::FileSystemError; use net_traits::filemanager_thread::FileManagerThreadError::FileSystemError;
let file = try!(File::open(file_path).map_err(|e| FileSystemError(e.to_string()))); let file = File::open(file_path).map_err(|e| FileSystemError(e.to_string()))?;
let metadata = try!(file.metadata().map_err(|e| FileSystemError(e.to_string()))); let metadata = file.metadata().map_err(|e| FileSystemError(e.to_string()))?;
let modified = try!(metadata.modified().map_err(|e| FileSystemError(e.to_string()))); let modified = metadata.modified().map_err(|e| FileSystemError(e.to_string()))?;
let elapsed = try!(modified.elapsed().map_err(|e| FileSystemError(e.to_string()))); let elapsed = modified.elapsed().map_err(|e| FileSystemError(e.to_string()))?;
// Unix Epoch: https://doc.servo.org/std/time/constant.UNIX_EPOCH.html // Unix Epoch: https://doc.servo.org/std/time/constant.UNIX_EPOCH.html
let modified_epoch = elapsed.as_secs() * 1000 + elapsed.subsec_nanos() as u64 / 1000000; let modified_epoch = elapsed.as_secs() * 1000 + elapsed.subsec_nanos() as u64 / 1000000;
let file_size = metadata.len(); let file_size = metadata.len();
let file_name = try!(file_path.file_name().ok_or(FileSystemError("Invalid filepath".to_string()))); let file_name = file_path.file_name().ok_or(FileSystemError("Invalid filepath".to_string()))?;
let file_impl = FileImpl::MetaDataOnly(FileMetaData { let file_impl = FileImpl::MetaDataOnly(FileMetaData {
path: file_path.to_path_buf(), path: file_path.to_path_buf(),
@ -400,7 +400,7 @@ impl FileManagerStore {
fn get_blob_buf(&self, sender: &IpcSender<FileManagerResult<ReadFileProgress>>, fn get_blob_buf(&self, sender: &IpcSender<FileManagerResult<ReadFileProgress>>,
id: &Uuid, origin_in: &FileOrigin, rel_pos: RelativePos, id: &Uuid, origin_in: &FileOrigin, rel_pos: RelativePos,
check_url_validity: bool) -> Result<(), BlobURLStoreError> { check_url_validity: bool) -> Result<(), BlobURLStoreError> {
let file_impl = try!(self.get_impl(id, origin_in, check_url_validity)); let file_impl = self.get_impl(id, origin_in, check_url_validity)?;
match file_impl { match file_impl {
FileImpl::Memory(buf) => { FileImpl::Memory(buf) => {
let range = rel_pos.to_abs_range(buf.size as usize); let range = rel_pos.to_abs_range(buf.size as usize);
@ -430,10 +430,10 @@ impl FileManagerStore {
let mime = guess_mime_type_opt(metadata.path.clone()); let mime = guess_mime_type_opt(metadata.path.clone());
let range = rel_pos.to_abs_range(metadata.size as usize); let range = rel_pos.to_abs_range(metadata.size as usize);
let mut file = try!(File::open(&metadata.path) let mut file = File::open(&metadata.path)
.map_err(|e| BlobURLStoreError::External(e.to_string()))); .map_err(|e| BlobURLStoreError::External(e.to_string()))?;
let seeked_start = try!(file.seek(SeekFrom::Start(range.start as u64)) let seeked_start = file.seek(SeekFrom::Start(range.start as u64))
.map_err(|e| BlobURLStoreError::External(e.to_string()))); .map_err(|e| BlobURLStoreError::External(e.to_string()))?;
if seeked_start == (range.start as u64) { if seeked_start == (range.start as u64) {
let type_string = match mime { let type_string = match mime {

View file

@ -317,7 +317,7 @@ impl StreamedResponse {
fn from_http_response(response: WrappedHttpResponse) -> io::Result<StreamedResponse> { fn from_http_response(response: WrappedHttpResponse) -> io::Result<StreamedResponse> {
let decoder = match response.content_encoding() { let decoder = match response.content_encoding() {
Some(Encoding::Gzip) => { Some(Encoding::Gzip) => {
Decoder::Gzip(try!(GzDecoder::new(response))) Decoder::Gzip(GzDecoder::new(response)?)
} }
Some(Encoding::Deflate) => { Some(Encoding::Deflate) => {
Decoder::Deflate(DeflateDecoder::new(response)) Decoder::Deflate(DeflateDecoder::new(response))
@ -1340,7 +1340,7 @@ fn cors_check(request: &Request, response: &Response) -> Result<(), ()> {
let origin = response.headers.get::<AccessControlAllowOrigin>().cloned(); let origin = response.headers.get::<AccessControlAllowOrigin>().cloned();
// Step 2 // Step 2
let origin = try!(origin.ok_or(())); let origin = origin.ok_or(())?;
// Step 3 // Step 3
if request.credentials_mode != CredentialsMode::Include && if request.credentials_mode != CredentialsMode::Include &&

View file

@ -53,9 +53,9 @@ fn decode_bytes_sync(key: LoadKey, bytes: &[u8]) -> DecoderMsg {
} }
fn get_placeholder_image(webrender_api: &webrender_traits::RenderApi, path: &PathBuf) -> io::Result<Arc<Image>> { fn get_placeholder_image(webrender_api: &webrender_traits::RenderApi, path: &PathBuf) -> io::Result<Arc<Image>> {
let mut file = try!(File::open(path)); let mut file = File::open(path)?;
let mut image_data = vec![]; let mut image_data = vec![];
try!(file.read_to_end(&mut image_data)); file.read_to_end(&mut image_data)?;
let mut image = load_from_memory(&image_data).unwrap(); let mut image = load_from_memory(&image_data).unwrap();
set_webrender_image_key(webrender_api, &mut image); set_webrender_image_key(webrender_api, &mut image);
Ok(Arc::new(image)) Ok(Arc::new(image))

View file

@ -169,14 +169,14 @@ impl MimeClassifier {
} }
pub fn validate(&self) -> Result<(), String> { pub fn validate(&self) -> Result<(), String> {
try!(self.image_classifier.validate()); self.image_classifier.validate()?;
try!(self.audio_video_classifier.validate()); self.audio_video_classifier.validate()?;
try!(self.scriptable_classifier.validate()); self.scriptable_classifier.validate()?;
try!(self.plaintext_classifier.validate()); self.plaintext_classifier.validate()?;
try!(self.archive_classifier.validate()); self.archive_classifier.validate()?;
try!(self.binary_or_plaintext.validate()); self.binary_or_plaintext.validate()?;
try!(self.feeds_classifier.validate()); self.feeds_classifier.validate()?;
try!(self.font_classifier.validate()); self.font_classifier.validate()?;
Ok(()) Ok(())
} }
@ -547,7 +547,7 @@ impl MIMEChecker for GroupedClassifier {
fn validate(&self) -> Result<(), String> { fn validate(&self) -> Result<(), String> {
for byte_matcher in &self.byte_matchers { for byte_matcher in &self.byte_matchers {
try!(byte_matcher.validate()) byte_matcher.validate()?
} }
Ok(()) Ok(())
} }

View file

@ -36,11 +36,11 @@ pub struct BlobBuf {
/// Parse URL as Blob URL scheme's definition /// Parse URL as Blob URL scheme's definition
/// https://w3c.github.io/FileAPI/#DefinitionOfScheme /// https://w3c.github.io/FileAPI/#DefinitionOfScheme
pub fn parse_blob_url(url: &ServoUrl) -> Result<(Uuid, FileOrigin), ()> { pub fn parse_blob_url(url: &ServoUrl) -> Result<(Uuid, FileOrigin), ()> {
let url_inner = try!(Url::parse(url.path()).map_err(|_| ())); let url_inner = Url::parse(url.path()).map_err(|_| ())?;
let id = { let id = {
let mut segs = try!(url_inner.path_segments().ok_or(())); let mut segs = url_inner.path_segments().ok_or(())?;
let id = try!(segs.nth(0).ok_or(())); let id = segs.nth(0).ok_or(())?;
try!(Uuid::from_str(id).map_err(|_| ())) Uuid::from_str(id).map_err(|_| ())?
}; };
Ok((id, get_blob_origin(&ServoUrl::from_url(url_inner)))) Ok((id, get_blob_origin(&ServoUrl::from_url(url_inner))))
} }

View file

@ -148,8 +148,8 @@ fn run_form_data_algorithm(root: &GlobalScope, bytes: Vec<u8>, mime: &[u8]) -> F
} else { } else {
"" ""
}; };
let mime: Mime = try!(mime_str.parse().map_err( let mime: Mime = mime_str.parse().map_err(
|_| Error::Type("Inappropriate MIME-type for Body".to_string()))); |_| Error::Type("Inappropriate MIME-type for Body".to_string()))?;
match mime { match mime {
// TODO // TODO
// ... Parser for Mime(TopLevel::Multipart, SubLevel::FormData, _) // ... Parser for Mime(TopLevel::Multipart, SubLevel::FormData, _)

View file

@ -390,7 +390,7 @@ pub unsafe fn private_from_proto_check<F>(mut obj: *mut JSObject,
-> Result<*const libc::c_void, ()> -> Result<*const libc::c_void, ()>
where F: Fn(&'static DOMClass) -> bool where F: Fn(&'static DOMClass) -> bool
{ {
let dom_class = try!(get_dom_class(obj).or_else(|_| { let dom_class = get_dom_class(obj).or_else(|_| {
if IsWrapper(obj) { if IsWrapper(obj) {
trace!("found wrapper"); trace!("found wrapper");
obj = UnwrapObject(obj, /* stopAtWindowProxy = */ 0); obj = UnwrapObject(obj, /* stopAtWindowProxy = */ 0);
@ -406,7 +406,7 @@ pub unsafe fn private_from_proto_check<F>(mut obj: *mut JSObject,
trace!("not a dom wrapper"); trace!("not a dom wrapper");
Err(()) Err(())
} }
})); })?;
if proto_check(dom_class) { if proto_check(dom_class) {
trace!("good prototype"); trace!("good prototype");

View file

@ -69,7 +69,7 @@ impl<T, C> FromJSValConvertible for MozMap<T>
return Err(()); return Err(());
} }
let property = match try!(T::from_jsval(cx, property.handle(), config.clone())) { let property = match T::from_jsval(cx, property.handle(), config.clone())? {
ConversionResult::Success(property) => property, ConversionResult::Success(property) => property,
ConversionResult::Failure(message) => return Ok(ConversionResult::Failure(message)), ConversionResult::Failure(message) => return Ok(ConversionResult::Failure(message)),
}; };

View file

@ -114,7 +114,7 @@ unsafe fn write_blob(blob: Root<Blob>,
w: *mut JSStructuredCloneWriter) w: *mut JSStructuredCloneWriter)
-> Result<(), ()> { -> Result<(), ()> {
let structured_writer = StructuredCloneWriter { w: w }; let structured_writer = StructuredCloneWriter { w: w };
let blob_vec = try!(blob.get_bytes()); let blob_vec = blob.get_bytes()?;
assert!(JS_WriteUint32Pair(w, StructuredCloneTags::DomBlob as u32, 0)); assert!(JS_WriteUint32Pair(w, StructuredCloneTags::DomBlob as u32, 0));
structured_writer.write_slice(&blob_vec); structured_writer.write_slice(&blob_vec);
structured_writer.write_str(&blob.type_string()); structured_writer.write_str(&blob.type_string());

View file

@ -32,7 +32,7 @@ pub fn validate_and_extract(namespace: Option<DOMString>,
let namespace = namespace_from_domstring(namespace); let namespace = namespace_from_domstring(namespace);
// Step 2. // Step 2.
try!(validate_qualified_name(qualified_name)); validate_qualified_name(qualified_name)?;
let colon = ':'; let colon = ':';

View file

@ -328,7 +328,7 @@ fn canonicalize_filter(filter: &BluetoothLEScanFilterInit) -> Fallible<Bluetooth
for service in services { for service in services {
// Step 3.2 - 3.3. // Step 3.2 - 3.3.
let uuid = try!(BluetoothUUID::service(service.clone())).to_string(); let uuid = BluetoothUUID::service(service.clone())?.to_string();
// Step 3.4. // Step 3.4.
if uuid_is_blocklisted(uuid.as_ref(), Blocklist::All) { if uuid_is_blocklisted(uuid.as_ref(), Blocklist::All) {
@ -393,7 +393,7 @@ fn canonicalize_filter(filter: &BluetoothLEScanFilterInit) -> Fallible<Bluetooth
// Step 7.3: No need to convert to IDL values since this is only used by native code. // Step 7.3: No need to convert to IDL values since this is only used by native code.
// Step 7.4 - 7.5. // Step 7.4 - 7.5.
map.insert(manufacturer_id, try!(canonicalize_bluetooth_data_filter_init(bdfi))); map.insert(manufacturer_id, canonicalize_bluetooth_data_filter_init(bdfi)?);
} }
Some(map) Some(map)
}, },
@ -417,7 +417,7 @@ fn canonicalize_filter(filter: &BluetoothLEScanFilterInit) -> Fallible<Bluetooth
}; };
// Step 9.3 - 9.4. // Step 9.3 - 9.4.
let service = try!(BluetoothUUID::service(service_name)).to_string(); let service = BluetoothUUID::service(service_name)?.to_string();
// Step 9.5. // Step 9.5.
if uuid_is_blocklisted(service.as_ref(), Blocklist::All) { if uuid_is_blocklisted(service.as_ref(), Blocklist::All) {
@ -427,7 +427,7 @@ fn canonicalize_filter(filter: &BluetoothLEScanFilterInit) -> Fallible<Bluetooth
// Step 9.6: No need to convert to IDL values since this is only used by native code. // Step 9.6: No need to convert to IDL values since this is only used by native code.
// Step 9.7 - 9.8. // Step 9.7 - 9.8.
map.insert(service, try!(canonicalize_bluetooth_data_filter_init(bdfi))); map.insert(service, canonicalize_bluetooth_data_filter_init(bdfi)?);
} }
Some(map) Some(map)
}, },

View file

@ -1137,18 +1137,18 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
// https://html.spec.whatwg.org/multipage/#img-error // https://html.spec.whatwg.org/multipage/#img-error
// If the image argument is an HTMLImageElement object that is in the broken state, // If the image argument is an HTMLImageElement object that is in the broken state,
// then throw an InvalidStateError exception // then throw an InvalidStateError exception
try!(self.fetch_image_data(image).ok_or(Error::InvalidState)) self.fetch_image_data(image).ok_or(Error::InvalidState)?
}, },
HTMLImageElementOrHTMLCanvasElementOrCanvasRenderingContext2D::HTMLCanvasElement(ref canvas) => { HTMLImageElementOrHTMLCanvasElementOrCanvasRenderingContext2D::HTMLCanvasElement(ref canvas) => {
let _ = canvas.get_or_init_2d_context(); let _ = canvas.get_or_init_2d_context();
try!(canvas.fetch_all_data().ok_or(Error::InvalidState)) canvas.fetch_all_data().ok_or(Error::InvalidState)?
}, },
HTMLImageElementOrHTMLCanvasElementOrCanvasRenderingContext2D::CanvasRenderingContext2D(ref context) => { HTMLImageElementOrHTMLCanvasElementOrCanvasRenderingContext2D::CanvasRenderingContext2D(ref context) => {
let canvas = context.Canvas(); let canvas = context.Canvas();
let _ = canvas.get_or_init_2d_context(); let _ = canvas.get_or_init_2d_context();
try!(canvas.fetch_all_data().ok_or(Error::InvalidState)) canvas.fetch_all_data().ok_or(Error::InvalidState)?
} }
}; };

View file

@ -293,11 +293,11 @@ impl DedicatedWorkerGlobalScope {
} }
let ret = sel.wait(); let ret = sel.wait();
if ret == worker_handle.id() { if ret == worker_handle.id() {
Ok(MixedMessage::FromWorker(try!(worker_port.recv()))) Ok(MixedMessage::FromWorker(worker_port.recv()?))
} else if ret == timer_event_handle.id() { } else if ret == timer_event_handle.id() {
Ok(MixedMessage::FromScheduler(try!(timer_event_port.recv()))) Ok(MixedMessage::FromScheduler(timer_event_port.recv()?))
} else if ret == devtools_handle.id() { } else if ret == devtools_handle.id() {
Ok(MixedMessage::FromDevtools(try!(devtools_port.recv()))) Ok(MixedMessage::FromDevtools(devtools_port.recv()?))
} else { } else {
panic!("unexpected select result!") panic!("unexpected select result!")
} }
@ -384,7 +384,7 @@ impl DedicatedWorkerGlobalScopeMethods for DedicatedWorkerGlobalScope {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-postmessage // https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-postmessage
unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult {
let data = try!(StructuredCloneData::write(cx, message)); let data = StructuredCloneData::write(cx, message)?;
let worker = self.worker.borrow().as_ref().unwrap().clone(); let worker = self.worker.borrow().as_ref().unwrap().clone();
self.parent_sender self.parent_sender
.send(CommonScriptMsg::RunnableMsg(WorkerEvent, .send(CommonScriptMsg::RunnableMsg(WorkerEvent,

View file

@ -146,7 +146,7 @@ impl DissimilarOriginWindowMethods for DissimilarOriginWindow {
// Step 1-2, 6-8. // Step 1-2, 6-8.
// TODO(#12717): Should implement the `transfer` argument. // TODO(#12717): Should implement the `transfer` argument.
let data = try!(StructuredCloneData::write(cx, message)); let data = StructuredCloneData::write(cx, message)?;
// Step 9. // Step 9.
self.post_message(origin, data); self.post_message(origin, data);

View file

@ -1454,7 +1454,7 @@ impl Document {
for node in nodes { for node in nodes {
match node { match node {
NodeOrString::Node(node) => { NodeOrString::Node(node) => {
try!(fragment.AppendChild(&node)); fragment.AppendChild(&node)?;
}, },
NodeOrString::String(string) => { NodeOrString::String(string) => {
let node = Root::upcast::<Node>(self.CreateTextNode(string)); let node = Root::upcast::<Node>(self.CreateTextNode(string));
@ -2819,8 +2819,8 @@ impl DocumentMethods for Document {
namespace: Option<DOMString>, namespace: Option<DOMString>,
qualified_name: DOMString) qualified_name: DOMString)
-> Fallible<Root<Element>> { -> Fallible<Root<Element>> {
let (namespace, prefix, local_name) = try!(validate_and_extract(namespace, let (namespace, prefix, local_name) = validate_and_extract(namespace,
&qualified_name)); &qualified_name)?;
let name = QualName::new(prefix, namespace, local_name); let name = QualName::new(prefix, namespace, local_name);
Ok(Element::create(name, self, ElementCreator::ScriptCreated)) Ok(Element::create(name, self, ElementCreator::ScriptCreated))
} }
@ -2845,8 +2845,8 @@ impl DocumentMethods for Document {
namespace: Option<DOMString>, namespace: Option<DOMString>,
qualified_name: DOMString) qualified_name: DOMString)
-> Fallible<Root<Attr>> { -> Fallible<Root<Attr>> {
let (namespace, prefix, local_name) = try!(validate_and_extract(namespace, let (namespace, prefix, local_name) = validate_and_extract(namespace,
&qualified_name)); &qualified_name)?;
let value = AttrValue::String("".to_owned()); let value = AttrValue::String("".to_owned());
let qualified_name = LocalName::from(qualified_name); let qualified_name = LocalName::from(qualified_name);
Ok(Attr::new(&self.window, Ok(Attr::new(&self.window,

View file

@ -57,7 +57,7 @@ impl DOMImplementationMethods for DOMImplementation {
pubid: DOMString, pubid: DOMString,
sysid: DOMString) sysid: DOMString)
-> Fallible<Root<DocumentType>> { -> Fallible<Root<DocumentType>> {
try!(validate_qualified_name(&qualified_name)); validate_qualified_name(&qualified_name)?;
Ok(DocumentType::new(qualified_name, Some(pubid), Some(sysid), &self.document)) Ok(DocumentType::new(qualified_name, Some(pubid), Some(sysid), &self.document))
} }

View file

@ -84,7 +84,7 @@ impl DOMTokenListMethods for DOMTokenList {
fn Add(&self, tokens: Vec<DOMString>) -> ErrorResult { fn Add(&self, tokens: Vec<DOMString>) -> ErrorResult {
let mut atoms = self.element.get_tokenlist_attribute(&self.local_name); let mut atoms = self.element.get_tokenlist_attribute(&self.local_name);
for token in &tokens { for token in &tokens {
let token = try!(self.check_token_exceptions(&token)); let token = self.check_token_exceptions(&token)?;
if !atoms.iter().any(|atom| *atom == token) { if !atoms.iter().any(|atom| *atom == token) {
atoms.push(token); atoms.push(token);
} }
@ -97,7 +97,7 @@ impl DOMTokenListMethods for DOMTokenList {
fn Remove(&self, tokens: Vec<DOMString>) -> ErrorResult { fn Remove(&self, tokens: Vec<DOMString>) -> ErrorResult {
let mut atoms = self.element.get_tokenlist_attribute(&self.local_name); let mut atoms = self.element.get_tokenlist_attribute(&self.local_name);
for token in &tokens { for token in &tokens {
let token = try!(self.check_token_exceptions(&token)); let token = self.check_token_exceptions(&token)?;
atoms.iter().position(|atom| *atom == token).map(|index| atoms.remove(index)); atoms.iter().position(|atom| *atom == token).map(|index| atoms.remove(index));
} }
self.element.set_atomic_tokenlist_attribute(&self.local_name, atoms); self.element.set_atomic_tokenlist_attribute(&self.local_name, atoms);
@ -107,7 +107,7 @@ impl DOMTokenListMethods for DOMTokenList {
// https://dom.spec.whatwg.org/#dom-domtokenlist-toggle // https://dom.spec.whatwg.org/#dom-domtokenlist-toggle
fn Toggle(&self, token: DOMString, force: Option<bool>) -> Fallible<bool> { fn Toggle(&self, token: DOMString, force: Option<bool>) -> Fallible<bool> {
let mut atoms = self.element.get_tokenlist_attribute(&self.local_name); let mut atoms = self.element.get_tokenlist_attribute(&self.local_name);
let token = try!(self.check_token_exceptions(&token)); let token = self.check_token_exceptions(&token)?;
match atoms.iter().position(|atom| *atom == token) { match atoms.iter().position(|atom| *atom == token) {
Some(index) => match force { Some(index) => match force {
Some(true) => Ok(true), Some(true) => Ok(true),

View file

@ -144,9 +144,9 @@ pub struct Element {
impl fmt::Debug for Element { impl fmt::Debug for Element {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "<{}", self.local_name)); write!(f, "<{}", self.local_name)?;
if let Some(ref id) = *self.id_attribute.borrow() { if let Some(ref id) = *self.id_attribute.borrow() {
try!(write!(f, " id={}", id)); write!(f, " id={}", id)?;
} }
write!(f, ">") write!(f, ">")
} }
@ -1532,7 +1532,7 @@ impl ElementMethods for Element {
qualified_name: DOMString, qualified_name: DOMString,
value: DOMString) -> ErrorResult { value: DOMString) -> ErrorResult {
let (namespace, prefix, local_name) = let (namespace, prefix, local_name) =
try!(validate_and_extract(namespace, &qualified_name)); validate_and_extract(namespace, &qualified_name)?;
let qualified_name = LocalName::from(qualified_name); let qualified_name = LocalName::from(qualified_name);
let value = self.parse_attribute(&namespace, &local_name, value); let value = self.parse_attribute(&namespace, &local_name, value);
self.set_first_matching_attribute( self.set_first_matching_attribute(
@ -1929,7 +1929,7 @@ impl ElementMethods for Element {
/// https://w3c.github.io/DOM-Parsing/#widl-Element-innerHTML /// https://w3c.github.io/DOM-Parsing/#widl-Element-innerHTML
fn SetInnerHTML(&self, value: DOMString) -> ErrorResult { fn SetInnerHTML(&self, value: DOMString) -> ErrorResult {
// Step 1. // Step 1.
let frag = try!(self.parse_fragment(value)); let frag = self.parse_fragment(value)?;
// Step 2. // Step 2.
// https://github.com/w3c/DOM-Parsing/issues/1 // https://github.com/w3c/DOM-Parsing/issues/1
let target = if let Some(template) = self.downcast::<HTMLTemplateElement>() { let target = if let Some(template) = self.downcast::<HTMLTemplateElement>() {
@ -1974,9 +1974,9 @@ impl ElementMethods for Element {
}; };
// Step 5. // Step 5.
let frag = try!(parent.parse_fragment(value)); let frag = parent.parse_fragment(value)?;
// Step 6. // Step 6.
try!(context_parent.ReplaceChild(frag.upcast(), context_node)); context_parent.ReplaceChild(frag.upcast(), context_node)?;
Ok(()) Ok(())
} }
@ -2095,8 +2095,8 @@ impl ElementMethods for Element {
// https://dom.spec.whatwg.org/#dom-element-insertadjacentelement // https://dom.spec.whatwg.org/#dom-element-insertadjacentelement
fn InsertAdjacentElement(&self, where_: DOMString, element: &Element) fn InsertAdjacentElement(&self, where_: DOMString, element: &Element)
-> Fallible<Option<Root<Element>>> { -> Fallible<Option<Root<Element>>> {
let where_ = try!(AdjacentPosition::try_from(&*where_)); let where_ = AdjacentPosition::try_from(&*where_)?;
let inserted_node = try!(self.insert_adjacent(where_, element.upcast())); let inserted_node = self.insert_adjacent(where_, element.upcast())?;
Ok(inserted_node.map(|node| Root::downcast(node).unwrap())) Ok(inserted_node.map(|node| Root::downcast(node).unwrap()))
} }
@ -2107,7 +2107,7 @@ impl ElementMethods for Element {
let text = Text::new(data, &document_from_node(self)); let text = Text::new(data, &document_from_node(self));
// Step 2. // Step 2.
let where_ = try!(AdjacentPosition::try_from(&*where_)); let where_ = AdjacentPosition::try_from(&*where_)?;
self.insert_adjacent(where_, text.upcast()).map(|_| ()) self.insert_adjacent(where_, text.upcast()).map(|_| ())
} }
@ -2115,7 +2115,7 @@ impl ElementMethods for Element {
fn InsertAdjacentHTML(&self, position: DOMString, text: DOMString) fn InsertAdjacentHTML(&self, position: DOMString, text: DOMString)
-> ErrorResult { -> ErrorResult {
// Step 1. // Step 1.
let position = try!(AdjacentPosition::try_from(&*position)); let position = AdjacentPosition::try_from(&*position)?;
let context = match position { let context = match position {
AdjacentPosition::BeforeBegin | AdjacentPosition::AfterEnd => { AdjacentPosition::BeforeBegin | AdjacentPosition::AfterEnd => {
@ -2137,7 +2137,7 @@ impl ElementMethods for Element {
&context.owner_doc(), context.downcast::<Element>()); &context.owner_doc(), context.downcast::<Element>());
// Step 3. // Step 3.
let fragment = try!(context.parse_fragment(text)); let fragment = context.parse_fragment(text)?;
// Step 4. // Step 4.
self.insert_adjacent(position, fragment.upcast()).map(|_| ()) self.insert_adjacent(position, fragment.upcast()).map(|_| ())

View file

@ -52,7 +52,7 @@ impl Headers {
pub fn Constructor(global: &GlobalScope, init: Option<HeadersInit>) pub fn Constructor(global: &GlobalScope, init: Option<HeadersInit>)
-> Fallible<Root<Headers>> { -> Fallible<Root<Headers>> {
let dom_headers_new = Headers::new(global); let dom_headers_new = Headers::new(global);
try!(dom_headers_new.fill(init)); dom_headers_new.fill(init)?;
Ok(dom_headers_new) Ok(dom_headers_new)
} }
} }
@ -63,7 +63,7 @@ impl HeadersMethods for Headers {
// Step 1 // Step 1
let value = normalize_value(value); let value = normalize_value(value);
// Step 2 // Step 2
let (mut valid_name, valid_value) = try!(validate_name_and_value(name, value)); let (mut valid_name, valid_value) = validate_name_and_value(name, value)?;
valid_name = valid_name.to_lowercase(); valid_name = valid_name.to_lowercase();
// Step 3 // Step 3
if self.guard.get() == Guard::Immutable { if self.guard.get() == Guard::Immutable {
@ -95,7 +95,7 @@ impl HeadersMethods for Headers {
// https://fetch.spec.whatwg.org/#dom-headers-delete // https://fetch.spec.whatwg.org/#dom-headers-delete
fn Delete(&self, name: ByteString) -> ErrorResult { fn Delete(&self, name: ByteString) -> ErrorResult {
// Step 1 // Step 1
let valid_name = try!(validate_name(name)); let valid_name = validate_name(name)?;
// Step 2 // Step 2
if self.guard.get() == Guard::Immutable { if self.guard.get() == Guard::Immutable {
return Err(Error::Type("Guard is immutable".to_string())); return Err(Error::Type("Guard is immutable".to_string()));
@ -121,7 +121,7 @@ impl HeadersMethods for Headers {
// https://fetch.spec.whatwg.org/#dom-headers-get // https://fetch.spec.whatwg.org/#dom-headers-get
fn Get(&self, name: ByteString) -> Fallible<Option<ByteString>> { fn Get(&self, name: ByteString) -> Fallible<Option<ByteString>> {
// Step 1 // Step 1
let valid_name = &try!(validate_name(name)); let valid_name = &validate_name(name)?;
Ok(self.header_list.borrow().get_raw(&valid_name).map(|v| { Ok(self.header_list.borrow().get_raw(&valid_name).map(|v| {
ByteString::new(v[0].clone()) ByteString::new(v[0].clone())
})) }))
@ -130,7 +130,7 @@ impl HeadersMethods for Headers {
// https://fetch.spec.whatwg.org/#dom-headers-has // https://fetch.spec.whatwg.org/#dom-headers-has
fn Has(&self, name: ByteString) -> Fallible<bool> { fn Has(&self, name: ByteString) -> Fallible<bool> {
// Step 1 // Step 1
let valid_name = try!(validate_name(name)); let valid_name = validate_name(name)?;
// Step 2 // Step 2
Ok(self.header_list.borrow_mut().get_raw(&valid_name).is_some()) Ok(self.header_list.borrow_mut().get_raw(&valid_name).is_some())
} }
@ -140,7 +140,7 @@ impl HeadersMethods for Headers {
// Step 1 // Step 1
let value = normalize_value(value); let value = normalize_value(value);
// Step 2 // Step 2
let (mut valid_name, valid_value) = try!(validate_name_and_value(name, value)); let (mut valid_name, valid_value) = validate_name_and_value(name, value)?;
valid_name = valid_name.to_lowercase(); valid_name = valid_name.to_lowercase();
// Step 3 // Step 3
if self.guard.get() == Guard::Immutable { if self.guard.get() == Guard::Immutable {
@ -172,10 +172,10 @@ impl Headers {
// Step 1 // Step 1
Some(HeadersInit::Headers(h)) => { Some(HeadersInit::Headers(h)) => {
for header in h.header_list.borrow().iter() { for header in h.header_list.borrow().iter() {
try!(self.Append( self.Append(
ByteString::new(Vec::from(header.name())), ByteString::new(Vec::from(header.name())),
ByteString::new(Vec::from(header.value_string().into_bytes())) ByteString::new(Vec::from(header.value_string().into_bytes()))
)); )?;
} }
Ok(()) Ok(())
}, },
@ -185,7 +185,7 @@ impl Headers {
if seq.len() == 2 { if seq.len() == 2 {
let val = seq.pop().unwrap(); let val = seq.pop().unwrap();
let name = seq.pop().unwrap(); let name = seq.pop().unwrap();
try!(self.Append(name, val)); self.Append(name, val)?;
} else { } else {
return Err(Error::Type( return Err(Error::Type(
format!("Each header object must be a sequence of length 2 - found one with length {}", format!("Each header object must be a sequence of length 2 - found one with length {}",
@ -198,7 +198,7 @@ impl Headers {
for (key, value) in m.iter() { for (key, value) in m.iter() {
let key_vec = key.as_ref().to_string().into(); let key_vec = key.as_ref().to_string().into();
let headers_key = ByteString::new(key_vec); let headers_key = ByteString::new(key_vec);
try!(self.Append(headers_key, value.clone())); self.Append(headers_key, value.clone())?;
} }
Ok(()) Ok(())
}, },
@ -360,7 +360,7 @@ pub fn is_forbidden_header_name(name: &str) -> bool {
// [4] https://www.rfc-editor.org/errata_search.php?rfc=7230 // [4] https://www.rfc-editor.org/errata_search.php?rfc=7230
fn validate_name_and_value(name: ByteString, value: ByteString) fn validate_name_and_value(name: ByteString, value: ByteString)
-> Fallible<(String, Vec<u8>)> { -> Fallible<(String, Vec<u8>)> {
let valid_name = try!(validate_name(name)); let valid_name = validate_name(name)?;
if !is_field_content(&value) { if !is_field_content(&value) {
return Err(Error::Type("Value is not valid".to_string())); return Err(Error::Type("Value is not valid".to_string()));
} }

View file

@ -297,9 +297,9 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement {
// Step 3. // Step 3.
let raw_data = match *self.context.borrow() { let raw_data = match *self.context.borrow() {
Some(CanvasContext::Context2d(ref context)) => { Some(CanvasContext::Context2d(ref context)) => {
let image_data = try!(context.GetImageData(Finite::wrap(0f64), Finite::wrap(0f64), let image_data = context.GetImageData(Finite::wrap(0f64), Finite::wrap(0f64),
Finite::wrap(self.Width() as f64), Finite::wrap(self.Width() as f64),
Finite::wrap(self.Height() as f64))); Finite::wrap(self.Height() as f64))?;
image_data.get_data_array() image_data.get_data_array()
} }
None => { None => {

View file

@ -49,7 +49,7 @@ impl HTMLOptionsCollection {
for _ in 0..count { for _ in 0..count {
let element = HTMLOptionElement::new(local_name!("option"), None, &document); let element = HTMLOptionElement::new(local_name!("option"), None, &document);
let node = element.upcast::<Node>(); let node = element.upcast::<Node>();
try!(root.AppendChild(node)); root.AppendChild(node)?;
}; };
Ok(()) Ok(())
} }
@ -90,7 +90,7 @@ impl HTMLOptionsCollectionMethods for HTMLOptionsCollection {
// Step 4 // Step 4
if n > 0 { if n > 0 {
try!(self.add_new_elements(n as u32)); self.add_new_elements(n as u32)?;
} }
// Step 5 // Step 5

View file

@ -103,7 +103,7 @@ impl HTMLTableElement {
let reference_element = node.child_elements().find(reference_predicate); let reference_element = node.child_elements().find(reference_predicate);
let reference_node = reference_element.r().map(|e| e.upcast()); let reference_node = reference_element.r().map(|e| e.upcast());
try!(node.InsertBefore(section.upcast(), reference_node)); node.InsertBefore(section.upcast(), reference_node)?;
} }
Ok(()) Ok(())

View file

@ -65,8 +65,8 @@ impl ImageData {
if let Some(jsobject) = opt_jsobject { if let Some(jsobject) = opt_jsobject {
let cx = global.get_cx(); let cx = global.get_cx();
typedarray!(in(cx) let array_res: Uint8ClampedArray = jsobject); typedarray!(in(cx) let array_res: Uint8ClampedArray = jsobject);
let mut array = try!(array_res let mut array = array_res
.map_err(|_| Error::Type("Argument to Image data is not an Uint8ClampedArray".to_owned()))); .map_err(|_| Error::Type("Argument to Image data is not an Uint8ClampedArray".to_owned()))?;
let byte_len = array.as_slice().len() as u32; let byte_len = array.as_slice().len() as u32;
if byte_len % 4 != 0 { if byte_len % 4 != 0 {

View file

@ -70,7 +70,7 @@ impl Location {
impl LocationMethods for Location { impl LocationMethods for Location {
// https://html.spec.whatwg.org/multipage/#dom-location-assign // https://html.spec.whatwg.org/multipage/#dom-location-assign
fn Assign(&self, url: USVString) -> ErrorResult { fn Assign(&self, url: USVString) -> ErrorResult {
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
// TODO: per spec, we should use the _API base URL_ specified by the // TODO: per spec, we should use the _API base URL_ specified by the
// _entry settings object_. // _entry settings object_.
let base_url = self.window.get_url(); let base_url = self.window.get_url();
@ -84,7 +84,7 @@ impl LocationMethods for Location {
// https://html.spec.whatwg.org/multipage/#dom-location-reload // https://html.spec.whatwg.org/multipage/#dom-location-reload
fn Reload(&self) -> ErrorResult { fn Reload(&self) -> ErrorResult {
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
self.window.load_url(self.get_url(), true, true, None); self.window.load_url(self.get_url(), true, true, None);
Ok(()) Ok(())
} }
@ -105,7 +105,7 @@ impl LocationMethods for Location {
// https://html.spec.whatwg.org/multipage/#dom-location-hash // https://html.spec.whatwg.org/multipage/#dom-location-hash
fn GetHash(&self) -> Fallible<USVString> { fn GetHash(&self) -> Fallible<USVString> {
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
Ok(UrlHelper::Hash(&self.get_url())) Ok(UrlHelper::Hash(&self.get_url()))
} }
@ -114,46 +114,46 @@ impl LocationMethods for Location {
if value.0.is_empty() { if value.0.is_empty() {
value = USVString("#".to_owned()); value = USVString("#".to_owned());
} }
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
self.set_url_component(value, UrlHelper::SetHash); self.set_url_component(value, UrlHelper::SetHash);
Ok(()) Ok(())
} }
// https://html.spec.whatwg.org/multipage/#dom-location-host // https://html.spec.whatwg.org/multipage/#dom-location-host
fn GetHost(&self) -> Fallible<USVString> { fn GetHost(&self) -> Fallible<USVString> {
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
Ok(UrlHelper::Host(&self.get_url())) Ok(UrlHelper::Host(&self.get_url()))
} }
// https://html.spec.whatwg.org/multipage/#dom-location-host // https://html.spec.whatwg.org/multipage/#dom-location-host
fn SetHost(&self, value: USVString) -> ErrorResult { fn SetHost(&self, value: USVString) -> ErrorResult {
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
self.set_url_component(value, UrlHelper::SetHost); self.set_url_component(value, UrlHelper::SetHost);
Ok(()) Ok(())
} }
// https://html.spec.whatwg.org/multipage/#dom-location-origin // https://html.spec.whatwg.org/multipage/#dom-location-origin
fn GetOrigin(&self) -> Fallible<USVString> { fn GetOrigin(&self) -> Fallible<USVString> {
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
Ok(UrlHelper::Origin(&self.get_url())) Ok(UrlHelper::Origin(&self.get_url()))
} }
// https://html.spec.whatwg.org/multipage/#dom-location-hostname // https://html.spec.whatwg.org/multipage/#dom-location-hostname
fn GetHostname(&self) -> Fallible<USVString> { fn GetHostname(&self) -> Fallible<USVString> {
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
Ok(UrlHelper::Hostname(&self.get_url())) Ok(UrlHelper::Hostname(&self.get_url()))
} }
// https://html.spec.whatwg.org/multipage/#dom-location-hostname // https://html.spec.whatwg.org/multipage/#dom-location-hostname
fn SetHostname(&self, value: USVString) -> ErrorResult { fn SetHostname(&self, value: USVString) -> ErrorResult {
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
self.set_url_component(value, UrlHelper::SetHostname); self.set_url_component(value, UrlHelper::SetHostname);
Ok(()) Ok(())
} }
// https://html.spec.whatwg.org/multipage/#dom-location-href // https://html.spec.whatwg.org/multipage/#dom-location-href
fn GetHref(&self) -> Fallible<USVString> { fn GetHref(&self) -> Fallible<USVString> {
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
Ok(UrlHelper::Href(&self.get_url())) Ok(UrlHelper::Href(&self.get_url()))
} }
@ -170,57 +170,57 @@ impl LocationMethods for Location {
// https://html.spec.whatwg.org/multipage/#dom-location-pathname // https://html.spec.whatwg.org/multipage/#dom-location-pathname
fn GetPathname(&self) -> Fallible<USVString> { fn GetPathname(&self) -> Fallible<USVString> {
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
Ok(UrlHelper::Pathname(&self.get_url())) Ok(UrlHelper::Pathname(&self.get_url()))
} }
// https://html.spec.whatwg.org/multipage/#dom-location-pathname // https://html.spec.whatwg.org/multipage/#dom-location-pathname
fn SetPathname(&self, value: USVString) -> ErrorResult { fn SetPathname(&self, value: USVString) -> ErrorResult {
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
self.set_url_component(value, UrlHelper::SetPathname); self.set_url_component(value, UrlHelper::SetPathname);
Ok(()) Ok(())
} }
// https://html.spec.whatwg.org/multipage/#dom-location-port // https://html.spec.whatwg.org/multipage/#dom-location-port
fn GetPort(&self) -> Fallible<USVString> { fn GetPort(&self) -> Fallible<USVString> {
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
Ok(UrlHelper::Port(&self.get_url())) Ok(UrlHelper::Port(&self.get_url()))
} }
// https://html.spec.whatwg.org/multipage/#dom-location-port // https://html.spec.whatwg.org/multipage/#dom-location-port
fn SetPort(&self, value: USVString) -> ErrorResult { fn SetPort(&self, value: USVString) -> ErrorResult {
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
self.set_url_component(value, UrlHelper::SetPort); self.set_url_component(value, UrlHelper::SetPort);
Ok(()) Ok(())
} }
// https://html.spec.whatwg.org/multipage/#dom-location-protocol // https://html.spec.whatwg.org/multipage/#dom-location-protocol
fn GetProtocol(&self) -> Fallible<USVString> { fn GetProtocol(&self) -> Fallible<USVString> {
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
Ok(UrlHelper::Protocol(&self.get_url())) Ok(UrlHelper::Protocol(&self.get_url()))
} }
// https://html.spec.whatwg.org/multipage/#dom-location-protocol // https://html.spec.whatwg.org/multipage/#dom-location-protocol
fn SetProtocol(&self, value: USVString) -> ErrorResult { fn SetProtocol(&self, value: USVString) -> ErrorResult {
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
self.set_url_component(value, UrlHelper::SetProtocol); self.set_url_component(value, UrlHelper::SetProtocol);
Ok(()) Ok(())
} }
// https://html.spec.whatwg.org/multipage/#dom-location-href // https://html.spec.whatwg.org/multipage/#dom-location-href
fn Stringifier(&self) -> Fallible<DOMString> { fn Stringifier(&self) -> Fallible<DOMString> {
Ok(DOMString::from(try!(self.GetHref()).0)) Ok(DOMString::from(self.GetHref()?.0))
} }
// https://html.spec.whatwg.org/multipage/#dom-location-search // https://html.spec.whatwg.org/multipage/#dom-location-search
fn GetSearch(&self) -> Fallible<USVString> { fn GetSearch(&self) -> Fallible<USVString> {
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
Ok(UrlHelper::Search(&self.get_url())) Ok(UrlHelper::Search(&self.get_url()))
} }
// https://html.spec.whatwg.org/multipage/#dom-location-search // https://html.spec.whatwg.org/multipage/#dom-location-search
fn SetSearch(&self, value: USVString) -> ErrorResult { fn SetSearch(&self, value: USVString) -> ErrorResult {
try!(self.check_same_origin_domain()); self.check_same_origin_domain()?;
self.set_url_component(value, UrlHelper::SetSearch); self.set_url_component(value, UrlHelper::SetSearch);
Ok(()) Ok(())
} }

View file

@ -631,7 +631,7 @@ impl Node {
let viable_previous_sibling = first_node_not_in(self.preceding_siblings(), &nodes); let viable_previous_sibling = first_node_not_in(self.preceding_siblings(), &nodes);
// Step 4. // Step 4.
let node = try!(self.owner_doc().node_from_nodes_and_strings(nodes)); let node = self.owner_doc().node_from_nodes_and_strings(nodes)?;
// Step 5. // Step 5.
let viable_previous_sibling = match viable_previous_sibling { let viable_previous_sibling = match viable_previous_sibling {
@ -640,7 +640,7 @@ impl Node {
}; };
// Step 6. // Step 6.
try!(Node::pre_insert(&node, &parent, viable_previous_sibling.r())); Node::pre_insert(&node, &parent, viable_previous_sibling.r())?;
Ok(()) Ok(())
} }
@ -660,10 +660,10 @@ impl Node {
let viable_next_sibling = first_node_not_in(self.following_siblings(), &nodes); let viable_next_sibling = first_node_not_in(self.following_siblings(), &nodes);
// Step 4. // Step 4.
let node = try!(self.owner_doc().node_from_nodes_and_strings(nodes)); let node = self.owner_doc().node_from_nodes_and_strings(nodes)?;
// Step 5. // Step 5.
try!(Node::pre_insert(&node, &parent, viable_next_sibling.r())); Node::pre_insert(&node, &parent, viable_next_sibling.r())?;
Ok(()) Ok(())
} }
@ -680,13 +680,13 @@ impl Node {
// Step 3. // Step 3.
let viable_next_sibling = first_node_not_in(self.following_siblings(), &nodes); let viable_next_sibling = first_node_not_in(self.following_siblings(), &nodes);
// Step 4. // Step 4.
let node = try!(self.owner_doc().node_from_nodes_and_strings(nodes)); let node = self.owner_doc().node_from_nodes_and_strings(nodes)?;
if self.parent_node == Some(&*parent) { if self.parent_node == Some(&*parent) {
// Step 5. // Step 5.
try!(parent.ReplaceChild(&node, self)); parent.ReplaceChild(&node, self)?;
} else { } else {
// Step 6. // Step 6.
try!(Node::pre_insert(&node, &parent, viable_next_sibling.r())); Node::pre_insert(&node, &parent, viable_next_sibling.r())?;
} }
Ok(()) Ok(())
} }
@ -695,7 +695,7 @@ impl Node {
pub fn prepend(&self, nodes: Vec<NodeOrString>) -> ErrorResult { pub fn prepend(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
// Step 1. // Step 1.
let doc = self.owner_doc(); let doc = self.owner_doc();
let node = try!(doc.node_from_nodes_and_strings(nodes)); let node = doc.node_from_nodes_and_strings(nodes)?;
// Step 2. // Step 2.
let first_child = self.first_child.get(); let first_child = self.first_child.get();
Node::pre_insert(&node, self, first_child.r()).map(|_| ()) Node::pre_insert(&node, self, first_child.r()).map(|_| ())
@ -705,7 +705,7 @@ impl Node {
pub fn append(&self, nodes: Vec<NodeOrString>) -> ErrorResult { pub fn append(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
// Step 1. // Step 1.
let doc = self.owner_doc(); let doc = self.owner_doc();
let node = try!(doc.node_from_nodes_and_strings(nodes)); let node = doc.node_from_nodes_and_strings(nodes)?;
// Step 2. // Step 2.
self.AppendChild(&node).map(|_| ()) self.AppendChild(&node).map(|_| ())
} }
@ -751,7 +751,7 @@ impl Node {
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn query_selector_all(&self, selectors: DOMString) -> Fallible<Root<NodeList>> { pub fn query_selector_all(&self, selectors: DOMString) -> Fallible<Root<NodeList>> {
let window = window_from_node(self); let window = window_from_node(self);
let iter = try!(self.query_selector_iter(selectors)); let iter = self.query_selector_iter(selectors)?;
Ok(NodeList::new_simple_list(&window, iter)) Ok(NodeList::new_simple_list(&window, iter))
} }
@ -852,7 +852,7 @@ impl Node {
{ {
let tr_node = tr.upcast::<Node>(); let tr_node = tr.upcast::<Node>();
if index == -1 { if index == -1 {
try!(self.InsertBefore(tr_node, None)); self.InsertBefore(tr_node, None)?;
} else { } else {
let items = get_items(); let items = get_items();
let node = match items.elements_iter() let node = match items.elements_iter()
@ -863,7 +863,7 @@ impl Node {
None => return Err(Error::IndexSize), None => return Err(Error::IndexSize),
Some(node) => node, Some(node) => node,
}; };
try!(self.InsertBefore(tr_node, node.r())); self.InsertBefore(tr_node, node.r())?;
} }
} }
@ -1566,7 +1566,7 @@ impl Node {
pub fn pre_insert(node: &Node, parent: &Node, child: Option<&Node>) pub fn pre_insert(node: &Node, parent: &Node, child: Option<&Node>)
-> Fallible<Root<Node>> { -> Fallible<Root<Node>> {
// Step 1. // Step 1.
try!(Node::ensure_pre_insertion_validity(node, parent, child)); Node::ensure_pre_insertion_validity(node, parent, child)?;
// Steps 2-3. // Steps 2-3.
let reference_child_root; let reference_child_root;

View file

@ -107,7 +107,7 @@ impl NodeIteratorMethods for NodeIterator {
before_node = false; before_node = false;
// Step 3-2. // Step 3-2.
let result = try!(self.accept_node(&node)); let result = self.accept_node(&node)?;
// Step 3-3. // Step 3-3.
if result == NodeFilterConstants::FILTER_ACCEPT { if result == NodeFilterConstants::FILTER_ACCEPT {
@ -122,7 +122,7 @@ impl NodeIteratorMethods for NodeIterator {
// Step 3-1. // Step 3-1.
for following_node in node.following_nodes(&self.root_node) { for following_node in node.following_nodes(&self.root_node) {
// Step 3-2. // Step 3-2.
let result = try!(self.accept_node(&following_node)); let result = self.accept_node(&following_node)?;
// Step 3-3. // Step 3-3.
if result == NodeFilterConstants::FILTER_ACCEPT { if result == NodeFilterConstants::FILTER_ACCEPT {
@ -151,7 +151,7 @@ impl NodeIteratorMethods for NodeIterator {
before_node = true; before_node = true;
// Step 3-2. // Step 3-2.
let result = try!(self.accept_node(&node)); let result = self.accept_node(&node)?;
// Step 3-3. // Step 3-3.
if result == NodeFilterConstants::FILTER_ACCEPT { if result == NodeFilterConstants::FILTER_ACCEPT {
@ -166,7 +166,7 @@ impl NodeIteratorMethods for NodeIterator {
// Step 3-1. // Step 3-1.
for preceding_node in node.preceding_nodes(&self.root_node) { for preceding_node in node.preceding_nodes(&self.root_node) {
// Step 3-2. // Step 3-2.
let result = try!(self.accept_node(&preceding_node)); let result = self.accept_node(&preceding_node)?;
// Step 3-3. // Step 3-3.
if result == NodeFilterConstants::FILTER_ACCEPT { if result == NodeFilterConstants::FILTER_ACCEPT {

View file

@ -269,25 +269,25 @@ impl RangeMethods for Range {
// https://dom.spec.whatwg.org/#dom-range-setstartbefore // https://dom.spec.whatwg.org/#dom-range-setstartbefore
fn SetStartBefore(&self, node: &Node) -> ErrorResult { fn SetStartBefore(&self, node: &Node) -> ErrorResult {
let parent = try!(node.GetParentNode().ok_or(Error::InvalidNodeType)); let parent = node.GetParentNode().ok_or(Error::InvalidNodeType)?;
self.SetStart(&parent, node.index()) self.SetStart(&parent, node.index())
} }
// https://dom.spec.whatwg.org/#dom-range-setstartafter // https://dom.spec.whatwg.org/#dom-range-setstartafter
fn SetStartAfter(&self, node: &Node) -> ErrorResult { fn SetStartAfter(&self, node: &Node) -> ErrorResult {
let parent = try!(node.GetParentNode().ok_or(Error::InvalidNodeType)); let parent = node.GetParentNode().ok_or(Error::InvalidNodeType)?;
self.SetStart(&parent, node.index() + 1) self.SetStart(&parent, node.index() + 1)
} }
// https://dom.spec.whatwg.org/#dom-range-setendbefore // https://dom.spec.whatwg.org/#dom-range-setendbefore
fn SetEndBefore(&self, node: &Node) -> ErrorResult { fn SetEndBefore(&self, node: &Node) -> ErrorResult {
let parent = try!(node.GetParentNode().ok_or(Error::InvalidNodeType)); let parent = node.GetParentNode().ok_or(Error::InvalidNodeType)?;
self.SetEnd(&parent, node.index()) self.SetEnd(&parent, node.index())
} }
// https://dom.spec.whatwg.org/#dom-range-setendafter // https://dom.spec.whatwg.org/#dom-range-setendafter
fn SetEndAfter(&self, node: &Node) -> ErrorResult { fn SetEndAfter(&self, node: &Node) -> ErrorResult {
let parent = try!(node.GetParentNode().ok_or(Error::InvalidNodeType)); let parent = node.GetParentNode().ok_or(Error::InvalidNodeType)?;
self.SetEnd(&parent, node.index() + 1) self.SetEnd(&parent, node.index() + 1)
} }
@ -303,7 +303,7 @@ impl RangeMethods for Range {
// https://dom.spec.whatwg.org/#dom-range-selectnode // https://dom.spec.whatwg.org/#dom-range-selectnode
fn SelectNode(&self, node: &Node) -> ErrorResult { fn SelectNode(&self, node: &Node) -> ErrorResult {
// Steps 1, 2. // Steps 1, 2.
let parent = try!(node.GetParentNode().ok_or(Error::InvalidNodeType)); let parent = node.GetParentNode().ok_or(Error::InvalidNodeType)?;
// Step 3. // Step 3.
let index = node.index(); let index = node.index();
// Step 4. // Step 4.
@ -446,7 +446,7 @@ impl RangeMethods for Range {
let data = cdata.SubstringData(start_offset, end_offset - start_offset).unwrap(); let data = cdata.SubstringData(start_offset, end_offset - start_offset).unwrap();
let clone = cdata.clone_with_data(data, &start_node.owner_doc()); let clone = cdata.clone_with_data(data, &start_node.owner_doc());
// Step 4.3. // Step 4.3.
try!(fragment.upcast::<Node>().AppendChild(&clone)); fragment.upcast::<Node>().AppendChild(&clone)?;
// Step 4.4 // Step 4.4
return Ok(fragment); return Ok(fragment);
} }
@ -454,7 +454,7 @@ impl RangeMethods for Range {
// Steps 5-12. // Steps 5-12.
let (first_contained_child, last_contained_child, contained_children) = let (first_contained_child, last_contained_child, contained_children) =
try!(self.contained_children()); self.contained_children()?;
if let Some(child) = first_contained_child { if let Some(child) = first_contained_child {
// Step 13. // Step 13.
@ -464,12 +464,12 @@ impl RangeMethods for Range {
let data = cdata.SubstringData(start_offset, start_node.len() - start_offset).unwrap(); let data = cdata.SubstringData(start_offset, start_node.len() - start_offset).unwrap();
let clone = cdata.clone_with_data(data, &start_node.owner_doc()); let clone = cdata.clone_with_data(data, &start_node.owner_doc());
// Step 13.3. // Step 13.3.
try!(fragment.upcast::<Node>().AppendChild(&clone)); fragment.upcast::<Node>().AppendChild(&clone)?;
} else { } else {
// Step 14.1. // Step 14.1.
let clone = child.CloneNode(false); let clone = child.CloneNode(false);
// Step 14.2. // Step 14.2.
try!(fragment.upcast::<Node>().AppendChild(&clone)); fragment.upcast::<Node>().AppendChild(&clone)?;
// Step 14.3. // Step 14.3.
let subrange = Range::new(&clone.owner_doc(), let subrange = Range::new(&clone.owner_doc(),
&start_node, &start_node,
@ -477,9 +477,9 @@ impl RangeMethods for Range {
&child, &child,
child.len()); child.len());
// Step 14.4. // Step 14.4.
let subfragment = try!(subrange.CloneContents()); let subfragment = subrange.CloneContents()?;
// Step 14.5. // Step 14.5.
try!(clone.AppendChild(subfragment.upcast())); clone.AppendChild(subfragment.upcast())?;
} }
} }
@ -488,7 +488,7 @@ impl RangeMethods for Range {
// Step 15.1. // Step 15.1.
let clone = child.CloneNode(true); let clone = child.CloneNode(true);
// Step 15.2. // Step 15.2.
try!(fragment.upcast::<Node>().AppendChild(&clone)); fragment.upcast::<Node>().AppendChild(&clone)?;
} }
if let Some(child) = last_contained_child { if let Some(child) = last_contained_child {
@ -499,12 +499,12 @@ impl RangeMethods for Range {
let data = cdata.SubstringData(0, end_offset).unwrap(); let data = cdata.SubstringData(0, end_offset).unwrap();
let clone = cdata.clone_with_data(data, &start_node.owner_doc()); let clone = cdata.clone_with_data(data, &start_node.owner_doc());
// Step 16.3. // Step 16.3.
try!(fragment.upcast::<Node>().AppendChild(&clone)); fragment.upcast::<Node>().AppendChild(&clone)?;
} else { } else {
// Step 17.1. // Step 17.1.
let clone = child.CloneNode(false); let clone = child.CloneNode(false);
// Step 17.2. // Step 17.2.
try!(fragment.upcast::<Node>().AppendChild(&clone)); fragment.upcast::<Node>().AppendChild(&clone)?;
// Step 17.3. // Step 17.3.
let subrange = Range::new(&clone.owner_doc(), let subrange = Range::new(&clone.owner_doc(),
&child, &child,
@ -512,9 +512,9 @@ impl RangeMethods for Range {
&end_node, &end_node,
end_offset); end_offset);
// Step 17.4. // Step 17.4.
let subfragment = try!(subrange.CloneContents()); let subfragment = subrange.CloneContents()?;
// Step 17.5. // Step 17.5.
try!(clone.AppendChild(subfragment.upcast())); clone.AppendChild(subfragment.upcast())?;
} }
} }
@ -547,11 +547,11 @@ impl RangeMethods for Range {
let text = end_data.SubstringData(start_offset, end_offset - start_offset); let text = end_data.SubstringData(start_offset, end_offset - start_offset);
clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap()); clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap());
// Step 4.3. // Step 4.3.
try!(fragment.upcast::<Node>().AppendChild(&clone)); fragment.upcast::<Node>().AppendChild(&clone)?;
// Step 4.4. // Step 4.4.
try!(end_data.ReplaceData(start_offset, end_data.ReplaceData(start_offset,
end_offset - start_offset, end_offset - start_offset,
DOMString::new())); DOMString::new())?;
// Step 4.5. // Step 4.5.
return Ok(fragment); return Ok(fragment);
} }
@ -559,7 +559,7 @@ impl RangeMethods for Range {
// Steps 5-12. // Steps 5-12.
let (first_contained_child, last_contained_child, contained_children) = let (first_contained_child, last_contained_child, contained_children) =
try!(self.contained_children()); self.contained_children()?;
let (new_node, new_offset) = if start_node.is_inclusive_ancestor_of(&end_node) { let (new_node, new_offset) = if start_node.is_inclusive_ancestor_of(&end_node) {
// Step 13. // Step 13.
@ -584,16 +584,16 @@ impl RangeMethods for Range {
start_node.len() - start_offset); start_node.len() - start_offset);
clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap()); clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap());
// Step 15.3. // Step 15.3.
try!(fragment.upcast::<Node>().AppendChild(&clone)); fragment.upcast::<Node>().AppendChild(&clone)?;
// Step 15.4. // Step 15.4.
try!(start_data.ReplaceData(start_offset, start_data.ReplaceData(start_offset,
start_node.len() - start_offset, start_node.len() - start_offset,
DOMString::new())); DOMString::new())?;
} else { } else {
// Step 16.1. // Step 16.1.
let clone = child.CloneNode(false); let clone = child.CloneNode(false);
// Step 16.2. // Step 16.2.
try!(fragment.upcast::<Node>().AppendChild(&clone)); fragment.upcast::<Node>().AppendChild(&clone)?;
// Step 16.3. // Step 16.3.
let subrange = Range::new(&clone.owner_doc(), let subrange = Range::new(&clone.owner_doc(),
&start_node, &start_node,
@ -601,15 +601,15 @@ impl RangeMethods for Range {
&child, &child,
child.len()); child.len());
// Step 16.4. // Step 16.4.
let subfragment = try!(subrange.ExtractContents()); let subfragment = subrange.ExtractContents()?;
// Step 16.5. // Step 16.5.
try!(clone.AppendChild(subfragment.upcast())); clone.AppendChild(subfragment.upcast())?;
} }
} }
// Step 17. // Step 17.
for child in contained_children { for child in contained_children {
try!(fragment.upcast::<Node>().AppendChild(&child)); fragment.upcast::<Node>().AppendChild(&child)?;
} }
if let Some(child) = last_contained_child { if let Some(child) = last_contained_child {
@ -621,14 +621,14 @@ impl RangeMethods for Range {
let text = end_data.SubstringData(0, end_offset); let text = end_data.SubstringData(0, end_offset);
clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap()); clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap());
// Step 18.3. // Step 18.3.
try!(fragment.upcast::<Node>().AppendChild(&clone)); fragment.upcast::<Node>().AppendChild(&clone)?;
// Step 18.4. // Step 18.4.
try!(end_data.ReplaceData(0, end_offset, DOMString::new())); end_data.ReplaceData(0, end_offset, DOMString::new())?;
} else { } else {
// Step 19.1. // Step 19.1.
let clone = child.CloneNode(false); let clone = child.CloneNode(false);
// Step 19.2. // Step 19.2.
try!(fragment.upcast::<Node>().AppendChild(&clone)); fragment.upcast::<Node>().AppendChild(&clone)?;
// Step 19.3. // Step 19.3.
let subrange = Range::new(&clone.owner_doc(), let subrange = Range::new(&clone.owner_doc(),
&child, &child,
@ -636,15 +636,15 @@ impl RangeMethods for Range {
&end_node, &end_node,
end_offset); end_offset);
// Step 19.4. // Step 19.4.
let subfragment = try!(subrange.ExtractContents()); let subfragment = subrange.ExtractContents()?;
// Step 19.5. // Step 19.5.
try!(clone.AppendChild(subfragment.upcast())); clone.AppendChild(subfragment.upcast())?;
} }
} }
// Step 20. // Step 20.
try!(self.SetStart(&new_node, new_offset)); self.SetStart(&new_node, new_offset)?;
try!(self.SetEnd(&new_node, new_offset)); self.SetEnd(&new_node, new_offset)?;
// Step 21. // Step 21.
Ok(fragment) Ok(fragment)
@ -690,16 +690,16 @@ impl RangeMethods for Range {
}; };
// Step 6. // Step 6.
try!(Node::ensure_pre_insertion_validity(node, Node::ensure_pre_insertion_validity(node,
&parent, &parent,
reference_node.r())); reference_node.r())?;
// Step 7. // Step 7.
let split_text; let split_text;
let reference_node = let reference_node =
match start_node.downcast::<Text>() { match start_node.downcast::<Text>() {
Some(text) => { Some(text) => {
split_text = try!(text.SplitText(start_offset)); split_text = text.SplitText(start_offset)?;
let new_reference = Root::upcast::<Node>(split_text); let new_reference = Root::upcast::<Node>(split_text);
assert!(new_reference.GetParentNode().r() == Some(&parent)); assert!(new_reference.GetParentNode().r() == Some(&parent));
Some(new_reference) Some(new_reference)
@ -729,7 +729,7 @@ impl RangeMethods for Range {
}; };
// Step 12. // Step 12.
try!(Node::pre_insert(node, &parent, reference_node.r())); Node::pre_insert(node, &parent, reference_node.r())?;
// Step 13. // Step 13.
if self.Collapsed() { if self.Collapsed() {
@ -839,16 +839,16 @@ impl RangeMethods for Range {
} }
// Step 3. // Step 3.
let fragment = try!(self.ExtractContents()); let fragment = self.ExtractContents()?;
// Step 4. // Step 4.
Node::replace_all(None, new_parent); Node::replace_all(None, new_parent);
// Step 5. // Step 5.
try!(self.InsertNode(new_parent)); self.InsertNode(new_parent)?;
// Step 6. // Step 6.
try!(new_parent.AppendChild(fragment.upcast())); new_parent.AppendChild(fragment.upcast())?;
// Step 7. // Step 7.
self.SelectNode(new_parent) self.SelectNode(new_parent)
@ -915,7 +915,7 @@ impl RangeMethods for Range {
let element = Element::fragment_parsing_context(&owner_doc, element.r()); let element = Element::fragment_parsing_context(&owner_doc, element.r());
// Step 3. // Step 3.
let fragment_node = try!(element.parse_fragment(fragment)); let fragment_node = element.parse_fragment(fragment)?;
// Step 4. // Step 4.
for node in fragment_node.upcast::<Node>().traverse_preorder() { for node in fragment_node.upcast::<Node>().traverse_preorder() {

View file

@ -308,12 +308,12 @@ impl Request {
headers_copy = Root::from_ref(&*init_headers); headers_copy = Root::from_ref(&*init_headers);
} }
&HeadersInit::ByteStringSequenceSequence(ref init_sequence) => { &HeadersInit::ByteStringSequenceSequence(ref init_sequence) => {
try!(headers_copy.fill(Some( headers_copy.fill(Some(
HeadersInit::ByteStringSequenceSequence(init_sequence.clone())))); HeadersInit::ByteStringSequenceSequence(init_sequence.clone())))?;
}, },
&HeadersInit::StringByteStringRecord(ref init_map) => { &HeadersInit::StringByteStringRecord(ref init_map) => {
try!(headers_copy.fill(Some( headers_copy.fill(Some(
HeadersInit::StringByteStringRecord(init_map.clone())))); HeadersInit::StringByteStringRecord(init_map.clone())))?;
}, },
} }
} }
@ -351,10 +351,10 @@ impl Request {
// but an input with headers is given, set request's // but an input with headers is given, set request's
// headers as the input's Headers. // headers as the input's Headers.
if let RequestInfo::Request(ref input_request) = input { if let RequestInfo::Request(ref input_request) = input {
try!(r.Headers().fill(Some(HeadersInit::Headers(input_request.Headers())))); r.Headers().fill(Some(HeadersInit::Headers(input_request.Headers())))?;
} }
}, },
Some(HeadersInit::Headers(_)) => try!(r.Headers().fill(Some(HeadersInit::Headers(headers_copy)))), Some(HeadersInit::Headers(_)) => r.Headers().fill(Some(HeadersInit::Headers(headers_copy)))?,
_ => {}, _ => {},
} }
@ -391,8 +391,8 @@ impl Request {
// Step 34.3 // Step 34.3
if let Some(contents) = content_type { if let Some(contents) = content_type {
if !r.Headers().Has(ByteString::new(b"Content-Type".to_vec())).unwrap() { if !r.Headers().Has(ByteString::new(b"Content-Type".to_vec())).unwrap() {
try!(r.Headers().Append(ByteString::new(b"Content-Type".to_vec()), r.Headers().Append(ByteString::new(b"Content-Type".to_vec()),
ByteString::new(contents.as_bytes().to_vec()))); ByteString::new(contents.as_bytes().to_vec()))?;
} }
} }
} }
@ -446,7 +446,7 @@ impl Request {
*r_clone.request.borrow_mut() = req.clone(); *r_clone.request.borrow_mut() = req.clone();
r_clone.body_used.set(body_used); r_clone.body_used.set(body_used);
*r_clone.mime_type.borrow_mut() = mime_type; *r_clone.mime_type.borrow_mut() = mime_type;
try!(r_clone.Headers().fill(Some(HeadersInit::Headers(r.Headers())))); r_clone.Headers().fill(Some(HeadersInit::Headers(r.Headers())))?;
r_clone.Headers().set_guard(headers_guard); r_clone.Headers().set_guard(headers_guard);
Ok(r_clone) Ok(r_clone)
} }

View file

@ -101,7 +101,7 @@ impl Response {
r.Headers().empty_header_list(); r.Headers().empty_header_list();
// Step 6.2 // Step 6.2
try!(r.Headers().fill(Some(headers_member.clone()))); r.Headers().fill(Some(headers_member.clone()))?;
} }
// Step 7 // Step 7
@ -119,8 +119,8 @@ impl Response {
// Step 7.4 // Step 7.4
if let Some(content_type_contents) = content_type { if let Some(content_type_contents) = content_type {
if !r.Headers().Has(ByteString::new(b"Content-Type".to_vec())).unwrap() { if !r.Headers().Has(ByteString::new(b"Content-Type".to_vec())).unwrap() {
try!(r.Headers().Append(ByteString::new(b"Content-Type".to_vec()), r.Headers().Append(ByteString::new(b"Content-Type".to_vec()),
ByteString::new(content_type_contents.as_bytes().to_vec()))); ByteString::new(content_type_contents.as_bytes().to_vec()))?;
} }
}; };
} }
@ -174,7 +174,7 @@ impl Response {
// Step 6 // Step 6
let url_bytestring = ByteString::from_str(url.as_str()).unwrap_or(ByteString::new(b"".to_vec())); let url_bytestring = ByteString::from_str(url.as_str()).unwrap_or(ByteString::new(b"".to_vec()));
try!(r.Headers().Set(ByteString::new(b"Location".to_vec()), url_bytestring)); r.Headers().Set(ByteString::new(b"Location".to_vec()), url_bytestring)?;
// Step 4 continued // Step 4 continued
// Headers Guard is set to Immutable here to prevent error in Step 6 // Headers Guard is set to Immutable here to prevent error in Step 6
@ -305,7 +305,7 @@ impl ResponseMethods for Response {
// Step 2 // Step 2
let new_response = Response::new(&self.global()); let new_response = Response::new(&self.global());
new_response.Headers().set_guard(self.Headers().get_guard()); new_response.Headers().set_guard(self.Headers().get_guard());
try!(new_response.Headers().fill(Some(HeadersInit::Headers(self.Headers())))); new_response.Headers().fill(Some(HeadersInit::Headers(self.Headers())))?;
// https://fetch.spec.whatwg.org/#concept-response-clone // https://fetch.spec.whatwg.org/#concept-response-clone
// Instead of storing a net_traits::Response internally, we // Instead of storing a net_traits::Response internally, we

View file

@ -89,7 +89,7 @@ impl ServiceWorkerMethods for ServiceWorker {
return Err(Error::InvalidState); return Err(Error::InvalidState);
} }
// Step 7 // Step 7
let data = try!(StructuredCloneData::write(cx, message)); let data = StructuredCloneData::write(cx, message)?;
let msg_vec = DOMMessage(data.move_to_arraybuffer()); let msg_vec = DOMMessage(data.move_to_arraybuffer());
let _ = let _ =
self.global() self.global()

View file

@ -303,11 +303,11 @@ impl ServiceWorkerGlobalScope {
let ret = sel.wait(); let ret = sel.wait();
if ret == worker_handle.id() { if ret == worker_handle.id() {
Ok(MixedMessage::FromServiceWorker(try!(worker_port.recv()))) Ok(MixedMessage::FromServiceWorker(worker_port.recv()?))
}else if ret == devtools_handle.id() { }else if ret == devtools_handle.id() {
Ok(MixedMessage::FromDevtools(try!(devtools_port.recv()))) Ok(MixedMessage::FromDevtools(devtools_port.recv()?))
} else if ret == timer_port_handle.id() { } else if ret == timer_port_handle.id() {
Ok(MixedMessage::FromTimeoutThread(try!(timer_event_port.recv()))) Ok(MixedMessage::FromTimeoutThread(timer_event_port.recv()?))
} else { } else {
panic!("unexpected select result!") panic!("unexpected select result!")
} }

View file

@ -135,7 +135,7 @@ impl<'a> Serialize for &'a Node {
let ar: AttrRef = (&qname, &**value); let ar: AttrRef = (&qname, &**value);
ar ar
}); });
try!(serializer.start_elem(name.clone(), attr_refs)); serializer.start_elem(name.clone(), attr_refs)?;
} }
let children = if let Some(tpl) = node.downcast::<HTMLTemplateElement>() { let children = if let Some(tpl) = node.downcast::<HTMLTemplateElement>() {
@ -146,18 +146,18 @@ impl<'a> Serialize for &'a Node {
}; };
for handle in children { for handle in children {
try!((&*handle).serialize(serializer, IncludeNode)); (&*handle).serialize(serializer, IncludeNode)?;
} }
if traversal_scope == IncludeNode { if traversal_scope == IncludeNode {
try!(serializer.end_elem(name.clone())); serializer.end_elem(name.clone())?;
} }
Ok(()) Ok(())
}, },
(ChildrenOnly, NodeTypeId::Document(_)) => { (ChildrenOnly, NodeTypeId::Document(_)) => {
for handle in node.children() { for handle in node.children() {
try!((&*handle).serialize(serializer, IncludeNode)); (&*handle).serialize(serializer, IncludeNode)?;
} }
Ok(()) Ok(())
}, },

View file

@ -104,7 +104,7 @@ impl TreeWalkerMethods for TreeWalker {
node = n; node = n;
// "2. If node is not null and filtering node returns FILTER_ACCEPT, // "2. If node is not null and filtering node returns FILTER_ACCEPT,
// then set the currentNode attribute to node, return node." // then set the currentNode attribute to node, return node."
if NodeFilterConstants::FILTER_ACCEPT == try!(self.accept_node(&node)) { if NodeFilterConstants::FILTER_ACCEPT == self.accept_node(&node)? {
self.current_node.set(&node); self.current_node.set(&node);
return Ok(Some(node)) return Ok(Some(node))
} }
@ -163,7 +163,7 @@ impl TreeWalkerMethods for TreeWalker {
// "4. If result is FILTER_ACCEPT, then // "4. If result is FILTER_ACCEPT, then
// set the currentNode attribute to node and return node." // set the currentNode attribute to node and return node."
loop { loop {
let result = try!(self.accept_node(&node)); let result = self.accept_node(&node)?;
match result { match result {
NodeFilterConstants::FILTER_REJECT => break, NodeFilterConstants::FILTER_REJECT => break,
_ if node.GetFirstChild().is_some() => _ if node.GetFirstChild().is_some() =>
@ -192,7 +192,7 @@ impl TreeWalkerMethods for TreeWalker {
} }
// "5. Filter node and if the return value is FILTER_ACCEPT, then // "5. Filter node and if the return value is FILTER_ACCEPT, then
// set the currentNode attribute to node and return node." // set the currentNode attribute to node and return node."
if NodeFilterConstants::FILTER_ACCEPT == try!(self.accept_node(&node)) { if NodeFilterConstants::FILTER_ACCEPT == self.accept_node(&node)? {
self.current_node.set(&node); self.current_node.set(&node);
return Ok(Some(node)) return Ok(Some(node))
} }
@ -220,7 +220,7 @@ impl TreeWalkerMethods for TreeWalker {
// "1. Set node to its first child." // "1. Set node to its first child."
node = child; node = child;
// "2. Filter node and set result to the return value." // "2. Filter node and set result to the return value."
result = try!(self.accept_node(&node)); result = self.accept_node(&node)?;
// "3. If result is FILTER_ACCEPT, then // "3. If result is FILTER_ACCEPT, then
// set the currentNode attribute to node and return node." // set the currentNode attribute to node and return node."
if NodeFilterConstants::FILTER_ACCEPT == result { if NodeFilterConstants::FILTER_ACCEPT == result {
@ -238,7 +238,7 @@ impl TreeWalkerMethods for TreeWalker {
Some(n) => { Some(n) => {
node = n; node = n;
// "3. Filter node and set result to the return value." // "3. Filter node and set result to the return value."
result = try!(self.accept_node(&node)); result = self.accept_node(&node)?;
// "4. If result is FILTER_ACCEPT, then // "4. If result is FILTER_ACCEPT, then
// set the currentNode attribute to node and return node." // set the currentNode attribute to node and return node."
if NodeFilterConstants::FILTER_ACCEPT == result { if NodeFilterConstants::FILTER_ACCEPT == result {
@ -275,7 +275,7 @@ impl TreeWalker {
// 4. Main: Repeat these substeps: // 4. Main: Repeat these substeps:
'main: loop { 'main: loop {
// "1. Filter node and let result be the return value." // "1. Filter node and let result be the return value."
let result = try!(self.accept_node(&node)); let result = self.accept_node(&node)?;
match result { match result {
// "2. If result is FILTER_ACCEPT, then set the currentNode // "2. If result is FILTER_ACCEPT, then set the currentNode
// attribute to node and return node." // attribute to node and return node."
@ -350,7 +350,7 @@ impl TreeWalker {
// "1. Set node to sibling." // "1. Set node to sibling."
node = sibling_op.unwrap(); node = sibling_op.unwrap();
// "2. Filter node and let result be the return value." // "2. Filter node and let result be the return value."
let result = try!(self.accept_node(&node)); let result = self.accept_node(&node)?;
// "3. If result is FILTER_ACCEPT, then set the currentNode // "3. If result is FILTER_ACCEPT, then set the currentNode
// attribute to node and return node." // attribute to node and return node."
if NodeFilterConstants::FILTER_ACCEPT == result { if NodeFilterConstants::FILTER_ACCEPT == result {
@ -378,7 +378,7 @@ impl TreeWalker {
// "5. Filter node and if the return value is FILTER_ACCEPT, then return null." // "5. Filter node and if the return value is FILTER_ACCEPT, then return null."
Some(n) => { Some(n) => {
node = n; node = n;
if NodeFilterConstants::FILTER_ACCEPT == try!(self.accept_node(&node)) { if NodeFilterConstants::FILTER_ACCEPT == self.accept_node(&node)? {
return Ok(None) return Ok(None)
} }
} }

View file

@ -636,8 +636,8 @@ fn validate_layer(cx: *mut JSContext,
let ctx = layer.source.as_ref().map(|ref s| s.get_or_init_webgl_context(cx, None)).unwrap_or(None); let ctx = layer.source.as_ref().map(|ref s| s.get_or_init_webgl_context(cx, None)).unwrap_or(None);
if let Some(ctx) = ctx { if let Some(ctx) = ctx {
let mut data = WebVRLayer::default(); let mut data = WebVRLayer::default();
try!(parse_bounds(&layer.leftBounds, &mut data.left_bounds)); parse_bounds(&layer.leftBounds, &mut data.left_bounds)?;
try!(parse_bounds(&layer.rightBounds, &mut data.right_bounds)); parse_bounds(&layer.rightBounds, &mut data.right_bounds)?;
Ok((data, ctx)) Ok((data, ctx))
} else { } else {
Err("VRLayer source must be a WebGL Context") Err("VRLayer source must be a WebGL Context")

View file

@ -285,7 +285,7 @@ impl<'a> WebGLValidator for TexImage2DValidator<'a> {
width, width,
height, height,
border, border,
} = try!(self.common_validator.validate()); } = self.common_validator.validate()?;
// GL_INVALID_VALUE is generated if target is one of the six cube map 2D // GL_INVALID_VALUE is generated if target is one of the six cube map 2D
// image targets and the width and height parameters are not equal. // image targets and the width and height parameters are not equal.

View file

@ -1496,7 +1496,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
typedarray!(in(cx) let array_buffer: ArrayBuffer = data); typedarray!(in(cx) let array_buffer: ArrayBuffer = data);
let data_vec = match array_buffer { let data_vec = match array_buffer {
Ok(mut data) => data.as_slice().to_vec(), Ok(mut data) => data.as_slice().to_vec(),
Err(_) => try!(fallible_array_buffer_view_to_vec(cx, data)), Err(_) => fallible_array_buffer_view_to_vec(cx, data)?,
}; };
let bound_buffer = match target { let bound_buffer = match target {
@ -1564,7 +1564,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
typedarray!(in(cx) let array_buffer: ArrayBuffer = data); typedarray!(in(cx) let array_buffer: ArrayBuffer = data);
let data_vec = match array_buffer { let data_vec = match array_buffer {
Ok(mut data) => data.as_slice().to_vec(), Ok(mut data) => data.as_slice().to_vec(),
Err(_) => try!(fallible_array_buffer_view_to_vec(cx, data)), Err(_) => fallible_array_buffer_view_to_vec(cx, data)?,
}; };
let bound_buffer = match target { let bound_buffer = match target {
@ -1596,7 +1596,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8
unsafe fn CompressedTexImage2D(&self, cx: *mut JSContext, _target: u32, _level: i32, _internal_format: u32, unsafe fn CompressedTexImage2D(&self, cx: *mut JSContext, _target: u32, _level: i32, _internal_format: u32,
_width: i32, _height: i32, _border: i32, pixels: *mut JSObject) -> Fallible<()> { _width: i32, _height: i32, _border: i32, pixels: *mut JSObject) -> Fallible<()> {
let _data = try!(fallible_array_buffer_view_to_vec(cx, pixels) ); let _data = fallible_array_buffer_view_to_vec(cx, pixels)?;
// FIXME: No compressed texture format is currently supported, so error out as per // FIXME: No compressed texture format is currently supported, so error out as per
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#COMPRESSED_TEXTURE_SUPPORT // https://www.khronos.org/registry/webgl/specs/latest/1.0/#COMPRESSED_TEXTURE_SUPPORT
self.webgl_error(InvalidEnum); self.webgl_error(InvalidEnum);
@ -1608,7 +1608,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
unsafe fn CompressedTexSubImage2D(&self, cx: *mut JSContext, _target: u32, _level: i32, unsafe fn CompressedTexSubImage2D(&self, cx: *mut JSContext, _target: u32, _level: i32,
_xoffset: i32, _yoffset: i32, _width: i32, _height: i32, _xoffset: i32, _yoffset: i32, _width: i32, _height: i32,
_format: u32, pixels: *mut JSObject) -> Fallible<()> { _format: u32, pixels: *mut JSObject) -> Fallible<()> {
let _data = try!(fallible_array_buffer_view_to_vec(cx, pixels)); let _data = fallible_array_buffer_view_to_vec(cx, pixels)?;
// FIXME: No compressed texture format is currently supported, so error out as per // FIXME: No compressed texture format is currently supported, so error out as per
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#COMPRESSED_TEXTURE_SUPPORT // https://www.khronos.org/registry/webgl/specs/latest/1.0/#COMPRESSED_TEXTURE_SUPPORT
self.webgl_error(InvalidEnum); self.webgl_error(InvalidEnum);
@ -2682,7 +2682,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
uniform: Option<&WebGLUniformLocation>, uniform: Option<&WebGLUniformLocation>,
data: *mut JSObject) -> Fallible<()> { data: *mut JSObject) -> Fallible<()> {
assert!(!data.is_null()); assert!(!data.is_null());
let data_vec = try!(typed_array_or_sequence_to_vec::<Int32>(cx, data, ConversionBehavior::Default)); let data_vec = typed_array_or_sequence_to_vec::<Int32>(cx, data, ConversionBehavior::Default)?;
if self.validate_uniform_parameters(uniform, UniformSetterType::Int, &data_vec) { if self.validate_uniform_parameters(uniform, UniformSetterType::Int, &data_vec) {
self.ipc_renderer self.ipc_renderer
@ -2700,7 +2700,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
uniform: Option<&WebGLUniformLocation>, uniform: Option<&WebGLUniformLocation>,
data: *mut JSObject) -> Fallible<()> { data: *mut JSObject) -> Fallible<()> {
assert!(!data.is_null()); assert!(!data.is_null());
let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); let data_vec = typed_array_or_sequence_to_vec::<Float32>(cx, data, ())?;
if self.validate_uniform_parameters(uniform, UniformSetterType::Float, &data_vec) { if self.validate_uniform_parameters(uniform, UniformSetterType::Float, &data_vec) {
self.ipc_renderer self.ipc_renderer
@ -2729,7 +2729,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
uniform: Option<&WebGLUniformLocation>, uniform: Option<&WebGLUniformLocation>,
data: *mut JSObject) -> Fallible<()> { data: *mut JSObject) -> Fallible<()> {
assert!(!data.is_null()); assert!(!data.is_null());
let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); let data_vec = typed_array_or_sequence_to_vec::<Float32>(cx, data, ())?;
if self.validate_uniform_parameters(uniform, if self.validate_uniform_parameters(uniform,
UniformSetterType::FloatVec2, UniformSetterType::FloatVec2,
@ -2762,7 +2762,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
uniform: Option<&WebGLUniformLocation>, uniform: Option<&WebGLUniformLocation>,
data: *mut JSObject) -> Fallible<()> { data: *mut JSObject) -> Fallible<()> {
assert!(!data.is_null()); assert!(!data.is_null());
let data_vec = try!(typed_array_or_sequence_to_vec::<Int32>(cx, data, ConversionBehavior::Default)); let data_vec = typed_array_or_sequence_to_vec::<Int32>(cx, data, ConversionBehavior::Default)?;
if self.validate_uniform_parameters(uniform, if self.validate_uniform_parameters(uniform,
UniformSetterType::IntVec2, UniformSetterType::IntVec2,
@ -2795,7 +2795,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
uniform: Option<&WebGLUniformLocation>, uniform: Option<&WebGLUniformLocation>,
data: *mut JSObject) -> Fallible<()> { data: *mut JSObject) -> Fallible<()> {
assert!(!data.is_null()); assert!(!data.is_null());
let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); let data_vec = typed_array_or_sequence_to_vec::<Float32>(cx, data, ())?;
if self.validate_uniform_parameters(uniform, if self.validate_uniform_parameters(uniform,
UniformSetterType::FloatVec3, UniformSetterType::FloatVec3,
@ -2828,7 +2828,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
uniform: Option<&WebGLUniformLocation>, uniform: Option<&WebGLUniformLocation>,
data: *mut JSObject) -> Fallible<()> { data: *mut JSObject) -> Fallible<()> {
assert!(!data.is_null()); assert!(!data.is_null());
let data_vec = try!(typed_array_or_sequence_to_vec::<Int32>(cx, data, ConversionBehavior::Default)); let data_vec = typed_array_or_sequence_to_vec::<Int32>(cx, data, ConversionBehavior::Default)?;
if self.validate_uniform_parameters(uniform, if self.validate_uniform_parameters(uniform,
UniformSetterType::IntVec3, UniformSetterType::IntVec3,
@ -2862,7 +2862,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
uniform: Option<&WebGLUniformLocation>, uniform: Option<&WebGLUniformLocation>,
data: *mut JSObject) -> Fallible<()> { data: *mut JSObject) -> Fallible<()> {
assert!(!data.is_null()); assert!(!data.is_null());
let data_vec = try!(typed_array_or_sequence_to_vec::<Int32>(cx, data, ConversionBehavior::Default)); let data_vec = typed_array_or_sequence_to_vec::<Int32>(cx, data, ConversionBehavior::Default)?;
if self.validate_uniform_parameters(uniform, if self.validate_uniform_parameters(uniform,
UniformSetterType::IntVec4, UniformSetterType::IntVec4,
@ -2895,7 +2895,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
uniform: Option<&WebGLUniformLocation>, uniform: Option<&WebGLUniformLocation>,
data: *mut JSObject) -> Fallible<()> { data: *mut JSObject) -> Fallible<()> {
assert!(!data.is_null()); assert!(!data.is_null());
let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); let data_vec = typed_array_or_sequence_to_vec::<Float32>(cx, data, ())?;
if self.validate_uniform_parameters(uniform, if self.validate_uniform_parameters(uniform,
UniformSetterType::FloatVec4, UniformSetterType::FloatVec4,
@ -2916,7 +2916,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
transpose: bool, transpose: bool,
data: *mut JSObject) -> Fallible<()> { data: *mut JSObject) -> Fallible<()> {
assert!(!data.is_null()); assert!(!data.is_null());
let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); let data_vec = typed_array_or_sequence_to_vec::<Float32>(cx, data, ())?;
if self.validate_uniform_parameters(uniform, if self.validate_uniform_parameters(uniform,
UniformSetterType::FloatMat2, UniformSetterType::FloatMat2,
&data_vec) { &data_vec) {
@ -2936,7 +2936,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
transpose: bool, transpose: bool,
data: *mut JSObject) -> Fallible<()> { data: *mut JSObject) -> Fallible<()> {
assert!(!data.is_null()); assert!(!data.is_null());
let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); let data_vec = typed_array_or_sequence_to_vec::<Float32>(cx, data, ())?;
if self.validate_uniform_parameters(uniform, if self.validate_uniform_parameters(uniform,
UniformSetterType::FloatMat3, UniformSetterType::FloatMat3,
&data_vec) { &data_vec) {
@ -2956,7 +2956,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
transpose: bool, transpose: bool,
data: *mut JSObject) -> Fallible<()> { data: *mut JSObject) -> Fallible<()> {
assert!(!data.is_null()); assert!(!data.is_null());
let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); let data_vec = typed_array_or_sequence_to_vec::<Float32>(cx, data, ())?;
if self.validate_uniform_parameters(uniform, if self.validate_uniform_parameters(uniform,
UniformSetterType::FloatMat4, UniformSetterType::FloatMat4,
&data_vec) { &data_vec) {
@ -2996,7 +2996,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn VertexAttrib1fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { unsafe fn VertexAttrib1fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> {
assert!(!data.is_null()); assert!(!data.is_null());
let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); let data_vec = typed_array_or_sequence_to_vec::<Float32>(cx, data, ())?;
if data_vec.len() < 1 { if data_vec.len() < 1 {
return Ok(self.webgl_error(InvalidOperation)); return Ok(self.webgl_error(InvalidOperation));
} }
@ -3013,7 +3013,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn VertexAttrib2fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { unsafe fn VertexAttrib2fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> {
assert!(!data.is_null()); assert!(!data.is_null());
let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); let data_vec = typed_array_or_sequence_to_vec::<Float32>(cx, data, ())?;
if data_vec.len() < 2 { if data_vec.len() < 2 {
return Ok(self.webgl_error(InvalidOperation)); return Ok(self.webgl_error(InvalidOperation));
} }
@ -3030,7 +3030,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn VertexAttrib3fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { unsafe fn VertexAttrib3fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> {
assert!(!data.is_null()); assert!(!data.is_null());
let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); let data_vec = typed_array_or_sequence_to_vec::<Float32>(cx, data, ())?;
if data_vec.len() < 3 { if data_vec.len() < 3 {
return Ok(self.webgl_error(InvalidOperation)); return Ok(self.webgl_error(InvalidOperation));
} }
@ -3047,7 +3047,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn VertexAttrib4fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { unsafe fn VertexAttrib4fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> {
assert!(!data.is_null()); assert!(!data.is_null());
let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); let data_vec = typed_array_or_sequence_to_vec::<Float32>(cx, data, ())?;
if data_vec.len() < 4 { if data_vec.len() < 4 {
return Ok(self.webgl_error(InvalidOperation)); return Ok(self.webgl_error(InvalidOperation));
} }
@ -3134,7 +3134,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
let data = if data_ptr.is_null() { let data = if data_ptr.is_null() {
None None
} else { } else {
Some(try!(fallible_array_buffer_view_to_vec(cx, data_ptr))) Some(fallible_array_buffer_view_to_vec(cx, data_ptr)?)
}; };
let validator = TexImage2DValidator::new(self, target, level, let validator = TexImage2DValidator::new(self, target, level,
@ -3261,7 +3261,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
let data = if data_ptr.is_null() { let data = if data_ptr.is_null() {
None None
} else { } else {
Some(try!(fallible_array_buffer_view_to_vec(cx, data_ptr))) Some(fallible_array_buffer_view_to_vec(cx, data_ptr)?)
}; };
let validator = TexImage2DValidator::new(self, target, level, let validator = TexImage2DValidator::new(self, target, level,

View file

@ -316,7 +316,7 @@ impl WebSocketMethods for WebSocket {
// https://html.spec.whatwg.org/multipage/#dom-websocket-send // https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send(&self, data: USVString) -> ErrorResult { fn Send(&self, data: USVString) -> ErrorResult {
let data_byte_len = data.0.as_bytes().len() as u64; let data_byte_len = data.0.as_bytes().len() as u64;
let send_data = try!(self.send_impl(data_byte_len)); let send_data = self.send_impl(data_byte_len)?;
if send_data { if send_data {
let mut other_sender = self.sender.borrow_mut(); let mut other_sender = self.sender.borrow_mut();
@ -334,7 +334,7 @@ impl WebSocketMethods for WebSocket {
If the buffer limit is reached in the first place, there are likely other major problems If the buffer limit is reached in the first place, there are likely other major problems
*/ */
let data_byte_len = blob.Size(); let data_byte_len = blob.Size();
let send_data = try!(self.send_impl(data_byte_len)); let send_data = self.send_impl(data_byte_len)?;
if send_data { if send_data {
let mut other_sender = self.sender.borrow_mut(); let mut other_sender = self.sender.borrow_mut();

View file

@ -765,7 +765,7 @@ impl WindowMethods for Window {
// Step 1-2, 6-8. // Step 1-2, 6-8.
// TODO(#12717): Should implement the `transfer` argument. // TODO(#12717): Should implement the `transfer` argument.
let data = try!(StructuredCloneData::write(cx, message)); let data = StructuredCloneData::write(cx, message)?;
// Step 9. // Step 9.
self.post_message(origin, data); self.post_message(origin, data);
@ -993,9 +993,9 @@ impl WindowMethods for Window {
// check-tidy: no specs after this line // check-tidy: no specs after this line
fn OpenURLInDefaultBrowser(&self, href: DOMString) -> ErrorResult { fn OpenURLInDefaultBrowser(&self, href: DOMString) -> ErrorResult {
let url = try!(ServoUrl::parse(&href).map_err(|e| { let url = ServoUrl::parse(&href).map_err(|e| {
Error::Type(format!("Couldn't parse URL: {}", e)) Error::Type(format!("Couldn't parse URL: {}", e))
})); })?;
match open::that(url.as_str()) { match open::that(url.as_str()) {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(e) => Err(Error::Type(format!("Couldn't open URL: {}", e))), Err(e) => Err(Error::Type(format!("Couldn't open URL: {}", e))),

View file

@ -167,7 +167,7 @@ impl WorkerMethods for Worker {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-worker-postmessage // https://html.spec.whatwg.org/multipage/#dom-worker-postmessage
unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult {
let data = try!(StructuredCloneData::write(cx, message)); let data = StructuredCloneData::write(cx, message)?;
let address = Trusted::new(self); let address = Trusted::new(self);
// NOTE: step 9 of https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage // NOTE: step 9 of https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage

View file

@ -501,7 +501,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest {
// Step 4 (first half) // Step 4 (first half)
let extracted_or_serialized = match data { let extracted_or_serialized = match data {
Some(DocumentOrBodyInit::Document(ref doc)) => { Some(DocumentOrBodyInit::Document(ref doc)) => {
let data = Vec::from(try!(serialize_document(&doc)).as_ref()); let data = Vec::from(serialize_document(&doc)?.as_ref());
let content_type = if doc.is_html_document() { let content_type = if doc.is_html_document() {
"text/html;charset=UTF-8" "text/html;charset=UTF-8"
} else { } else {
@ -719,7 +719,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest {
_ => {}, _ => {},
} }
// Step 2 // Step 2
let override_mime = try!(mime.parse::<Mime>().map_err(|_| Error::Syntax)); let override_mime = mime.parse::<Mime>().map_err(|_| Error::Syntax)?;
// Step 3 // Step 3
let mime_no_params = Mime(override_mime.clone().0, override_mime.clone().1, vec![]); let mime_no_params = Mime(override_mime.clone().0, override_mime.clone().1, vec![]);
*self.override_mime_type.borrow_mut() = Some(mime_no_params); *self.override_mime_type.borrow_mut() = Some(mime_no_params);

View file

@ -371,9 +371,9 @@ pub struct ServoLayoutElement<'le> {
impl<'le> fmt::Debug for ServoLayoutElement<'le> { impl<'le> fmt::Debug for ServoLayoutElement<'le> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "<{}", self.element.local_name())); write!(f, "<{}", self.element.local_name())?;
if let &Some(ref id) = unsafe { &*self.element.id_attribute() } { if let &Some(ref id) = unsafe { &*self.element.id_attribute() } {
try!(write!(f, " id={}", id)); write!(f, " id={}", id)?;
} }
write!(f, "> ({:#x})", self.as_node().opaque().0) write!(f, "> ({:#x})", self.as_node().opaque().0)
} }

View file

@ -96,7 +96,7 @@ impl Serialize for UntrustedNodeAddress {
impl<'de> Deserialize<'de> for UntrustedNodeAddress { impl<'de> Deserialize<'de> for UntrustedNodeAddress {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<UntrustedNodeAddress, D::Error> { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<UntrustedNodeAddress, D::Error> {
let value: usize = try!(Deserialize::deserialize(d)); let value: usize = Deserialize::deserialize(d)?;
Ok(UntrustedNodeAddress::from_id(value)) Ok(UntrustedNodeAddress::from_id(value))
} }
} }

View file

@ -1819,7 +1819,7 @@ pub mod tests {
-> Result<PseudoClass, -> Result<PseudoClass,
ParseError<'i, SelectorParseError<'i, ()>>> { ParseError<'i, SelectorParseError<'i, ()>>> {
match_ignore_ascii_case! { &name, match_ignore_ascii_case! { &name,
"lang" => Ok(PseudoClass::Lang(try!(parser.expect_ident_or_string()).into_owned())), "lang" => Ok(PseudoClass::Lang(parser.expect_ident_or_string()?.into_owned())),
_ => Err(SelectorParseError::Custom(()).into()) _ => Err(SelectorParseError::Custom(()).into())
} }
} }

View file

@ -512,8 +512,8 @@ pub fn parse_legacy_color(mut input: &str) -> Result<RGBA, ()> {
0 => Err(()), 0 => Err(()),
1 => hex(string[0] as char), 1 => hex(string[0] as char),
_ => { _ => {
let upper = try!(hex(string[0] as char)); let upper = hex(string[0] as char)?;
let lower = try!(hex(string[1] as char)); let lower = hex(string[1] as char)?;
Ok((upper << 4) | lower) Ok((upper << 4) | lower)
} }
} }

View file

@ -220,22 +220,22 @@ impl<'a> Add for &'a TraversalStatistics {
impl fmt::Display for TraversalStatistics { impl fmt::Display for TraversalStatistics {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
debug_assert!(self.traversal_time_ms != 0.0, "should have set traversal time"); debug_assert!(self.traversal_time_ms != 0.0, "should have set traversal time");
try!(writeln!(f, "[PERF] perf block start")); writeln!(f, "[PERF] perf block start")?;
try!(writeln!(f, "[PERF],traversal,{}", if self.is_parallel.unwrap() { writeln!(f, "[PERF],traversal,{}", if self.is_parallel.unwrap() {
"parallel" "parallel"
} else { } else {
"sequential" "sequential"
})); })?;
try!(writeln!(f, "[PERF],elements_traversed,{}", self.elements_traversed)); writeln!(f, "[PERF],elements_traversed,{}", self.elements_traversed)?;
try!(writeln!(f, "[PERF],elements_styled,{}", self.elements_styled)); writeln!(f, "[PERF],elements_styled,{}", self.elements_styled)?;
try!(writeln!(f, "[PERF],elements_matched,{}", self.elements_matched)); writeln!(f, "[PERF],elements_matched,{}", self.elements_matched)?;
try!(writeln!(f, "[PERF],styles_shared,{}", self.styles_shared)); writeln!(f, "[PERF],styles_shared,{}", self.styles_shared)?;
try!(writeln!(f, "[PERF],selectors,{}", self.selectors)); writeln!(f, "[PERF],selectors,{}", self.selectors)?;
try!(writeln!(f, "[PERF],revalidation_selectors,{}", self.revalidation_selectors)); writeln!(f, "[PERF],revalidation_selectors,{}", self.revalidation_selectors)?;
try!(writeln!(f, "[PERF],dependency_selectors,{}", self.dependency_selectors)); writeln!(f, "[PERF],dependency_selectors,{}", self.dependency_selectors)?;
try!(writeln!(f, "[PERF],declarations,{}", self.declarations)); writeln!(f, "[PERF],declarations,{}", self.declarations)?;
try!(writeln!(f, "[PERF],stylist_rebuilds,{}", self.stylist_rebuilds)); writeln!(f, "[PERF],stylist_rebuilds,{}", self.stylist_rebuilds)?;
try!(writeln!(f, "[PERF],traversal_time_ms,{}", self.traversal_time_ms)); writeln!(f, "[PERF],traversal_time_ms,{}", self.traversal_time_ms)?;
writeln!(f, "[PERF] perf block end") writeln!(f, "[PERF] perf block end")
} }
} }

View file

@ -135,7 +135,7 @@ impl SpecifiedValue {
pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Box<Self>, ParseError<'i>> { -> Result<Box<Self>, ParseError<'i>> {
let mut references = Some(HashSet::new()); let mut references = Some(HashSet::new());
let (first, css, last) = try!(parse_self_contained_declaration_value(input, &mut references)); let (first, css, last) = parse_self_contained_declaration_value(input, &mut references)?;
Ok(Box::new(SpecifiedValue { Ok(Box::new(SpecifiedValue {
css: css.into_owned(), css: css.into_owned(),
first_token_type: first, first_token_type: first,
@ -149,7 +149,7 @@ impl SpecifiedValue {
pub fn parse_non_custom_with_var<'i, 't> pub fn parse_non_custom_with_var<'i, 't>
(input: &mut Parser<'i, 't>) (input: &mut Parser<'i, 't>)
-> Result<(TokenSerializationType, Cow<'i, str>), ParseError<'i>> { -> Result<(TokenSerializationType, Cow<'i, str>), ParseError<'i>> {
let (first_token_type, css, _) = try!(parse_self_contained_declaration_value(input, &mut None)); let (first_token_type, css, _) = parse_self_contained_declaration_value(input, &mut None)?;
Ok((first_token_type, css)) Ok((first_token_type, css))
} }
@ -163,8 +163,7 @@ fn parse_self_contained_declaration_value<'i, 't>
), ParseError<'i>> { ), ParseError<'i>> {
let start_position = input.position(); let start_position = input.position();
let mut missing_closing_characters = String::new(); let mut missing_closing_characters = String::new();
let (first, last) = try!( let (first, last) = parse_declaration_value(input, references, &mut missing_closing_characters)?;
parse_declaration_value(input, references, &mut missing_closing_characters));
let mut css: Cow<str> = input.slice_from(start_position).into(); let mut css: Cow<str> = input.slice_from(start_position).into();
if !missing_closing_characters.is_empty() { if !missing_closing_characters.is_empty() {
// Unescaped backslash at EOF in a quoted string is ignored. // Unescaped backslash at EOF in a quoted string is ignored.
@ -185,7 +184,7 @@ fn parse_declaration_value<'i, 't>
input.parse_until_before(Delimiter::Bang | Delimiter::Semicolon, |input| { input.parse_until_before(Delimiter::Bang | Delimiter::Semicolon, |input| {
// Need at least one token // Need at least one token
let start_position = input.position(); let start_position = input.position();
try!(input.next_including_whitespace()); input.next_including_whitespace()?;
input.reset(start_position); input.reset(start_position);
parse_declaration_value_block(input, references, missing_closing_characters) parse_declaration_value_block(input, references, missing_closing_characters)
@ -209,9 +208,9 @@ fn parse_declaration_value_block<'i, 't>
loop { loop {
macro_rules! nested { macro_rules! nested {
() => { () => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
parse_declaration_value_block(input, references, missing_closing_characters) parse_declaration_value_block(input, references, missing_closing_characters)
})) })?
} }
} }
macro_rules! check_closed { macro_rules! check_closed {
@ -243,9 +242,9 @@ fn parse_declaration_value_block<'i, 't>
Token::Function(ref name) => { Token::Function(ref name) => {
if name.eq_ignore_ascii_case("var") { if name.eq_ignore_ascii_case("var") {
let position = input.position(); let position = input.position();
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
parse_var_function(input, references) parse_var_function(input, references)
})); })?;
input.reset(position); input.reset(position);
} }
nested!(); nested!();
@ -311,21 +310,21 @@ fn parse_declaration_value_block<'i, 't>
fn parse_var_function<'i, 't>(input: &mut Parser<'i, 't>, fn parse_var_function<'i, 't>(input: &mut Parser<'i, 't>,
references: &mut Option<HashSet<Name>>) references: &mut Option<HashSet<Name>>)
-> Result<(), ParseError<'i>> { -> Result<(), ParseError<'i>> {
let name = try!(input.expect_ident()); let name = input.expect_ident()?;
let name: Result<_, ParseError> = let name: Result<_, ParseError> =
parse_name(&name) parse_name(&name)
.map_err(|()| SelectorParseError::UnexpectedIdent(name.clone()).into()); .map_err(|()| SelectorParseError::UnexpectedIdent(name.clone()).into());
let name = try!(name); let name = name?;
if input.try(|input| input.expect_comma()).is_ok() { if input.try(|input| input.expect_comma()).is_ok() {
// Exclude `!` and `;` at the top level // Exclude `!` and `;` at the top level
// https://drafts.csswg.org/css-syntax/#typedef-declaration-value // https://drafts.csswg.org/css-syntax/#typedef-declaration-value
try!(input.parse_until_before(Delimiter::Bang | Delimiter::Semicolon, |input| { input.parse_until_before(Delimiter::Bang | Delimiter::Semicolon, |input| {
// At least one non-comment token. // At least one non-comment token.
try!(input.next_including_whitespace()); input.next_including_whitespace()?;
// Skip until the end. // Skip until the end.
while let Ok(_) = input.next_including_whitespace_and_comments() {} while let Ok(_) = input.next_including_whitespace_and_comments() {}
Ok(()) Ok(())
})); })?;
} }
if let Some(ref mut refs) = *references { if let Some(ref mut refs) = *references {
refs.insert(Atom::from(name)); refs.insert(Atom::from(name));
@ -562,7 +561,7 @@ fn substitute_block<'i, 't, F>(input: &mut Parser<'i, 't>,
Token::Function(ref name) if name.eq_ignore_ascii_case("var") => { Token::Function(ref name) if name.eq_ignore_ascii_case("var") => {
partial_computed_value.push( partial_computed_value.push(
input.slice(position.0..before_this_token), position.1, last_token_type); input.slice(position.0..before_this_token), position.1, last_token_type);
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
// parse_var_function() ensures neither .unwrap() will fail. // parse_var_function() ensures neither .unwrap() will fail.
let name = input.expect_ident().unwrap(); let name = input.expect_ident().unwrap();
let name = Atom::from(parse_name(&name).unwrap()); let name = Atom::from(parse_name(&name).unwrap());
@ -574,7 +573,7 @@ fn substitute_block<'i, 't, F>(input: &mut Parser<'i, 't>,
// FIXME: Add a specialized method to cssparser to do this with less work. // FIXME: Add a specialized method to cssparser to do this with less work.
while let Ok(_) = input.next() {} while let Ok(_) = input.next() {}
} else { } else {
try!(input.expect_comma()); input.expect_comma()?;
let position = input.position(); let position = input.position();
let first_token_type = input.next_including_whitespace_and_comments() let first_token_type = input.next_including_whitespace_and_comments()
// parse_var_function() ensures that .unwrap() will not fail. // parse_var_function() ensures that .unwrap() will not fail.
@ -582,12 +581,12 @@ fn substitute_block<'i, 't, F>(input: &mut Parser<'i, 't>,
.serialization_type(); .serialization_type();
input.reset(position); input.reset(position);
let mut position = (position, first_token_type); let mut position = (position, first_token_type);
last_token_type = try!(substitute_block( last_token_type = substitute_block(
input, &mut position, partial_computed_value, substitute_one)); input, &mut position, partial_computed_value, substitute_one)?;
partial_computed_value.push_from(position, input, last_token_type); partial_computed_value.push_from(position, input, last_token_type);
} }
Ok(()) Ok(())
})); })?;
set_position_at_next_iteration = true set_position_at_next_iteration = true
} }
@ -595,9 +594,9 @@ fn substitute_block<'i, 't, F>(input: &mut Parser<'i, 't>,
Token::ParenthesisBlock | Token::ParenthesisBlock |
Token::CurlyBracketBlock | Token::CurlyBracketBlock |
Token::SquareBracketBlock => { Token::SquareBracketBlock => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
substitute_block(input, position, partial_computed_value, substitute_one) substitute_block(input, position, partial_computed_value, substitute_one)
})); })?;
// Its the same type for CloseCurlyBracket and CloseSquareBracket. // Its the same type for CloseCurlyBracket and CloseSquareBracket.
last_token_type = Token::CloseParenthesis.serialization_type(); last_token_type = Token::CloseParenthesis.serialization_type();
} }
@ -623,7 +622,7 @@ pub fn substitute<'i>(input: &'i str, first_token_type: TokenSerializationType,
let mut input = ParserInput::new(input); let mut input = ParserInput::new(input);
let mut input = Parser::new(&mut input); let mut input = Parser::new(&mut input);
let mut position = (input.position(), first_token_type); let mut position = (input.position(), first_token_type);
let last_token_type = try!(substitute_block( let last_token_type = substitute_block(
&mut input, &mut position, &mut substituted, &mut |name, substituted| { &mut input, &mut position, &mut substituted, &mut |name, substituted| {
if let Some(value) = computed_values_map.as_ref().and_then(|map| map.get(name)) { if let Some(value) = computed_values_map.as_ref().and_then(|map| map.get(name)) {
substituted.push_variable(value); substituted.push_variable(value);
@ -632,7 +631,7 @@ pub fn substitute<'i>(input: &'i str, first_token_type: TokenSerializationType,
Err(()) Err(())
} }
} }
)); )?;
substituted.push_from(position, &input, last_token_type); substituted.push_from(position, &input, last_token_type);
Ok(substituted.css) Ok(substituted.css)
} }

View file

@ -180,7 +180,7 @@ impl<N: TNode> Debug for ShowDataAndPrimaryValues<N> {
pub struct ShowSubtree<N: TNode>(pub N); pub struct ShowSubtree<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtree<N> { impl<N: TNode> Debug for ShowSubtree<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(f, "DOM Subtree:")); writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| write!(f, "{:?}", n), self.0, 1) fmt_subtree(f, &|f, n| write!(f, "{:?}", n), self.0, 1)
} }
} }
@ -190,7 +190,7 @@ impl<N: TNode> Debug for ShowSubtree<N> {
pub struct ShowSubtreeData<N: TNode>(pub N); pub struct ShowSubtreeData<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeData<N> { impl<N: TNode> Debug for ShowSubtreeData<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(f, "DOM Subtree:")); writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data(f, n), self.0, 1) fmt_subtree(f, &|f, n| fmt_with_data(f, n), self.0, 1)
} }
} }
@ -200,7 +200,7 @@ impl<N: TNode> Debug for ShowSubtreeData<N> {
pub struct ShowSubtreeDataAndPrimaryValues<N: TNode>(pub N); pub struct ShowSubtreeDataAndPrimaryValues<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeDataAndPrimaryValues<N> { impl<N: TNode> Debug for ShowSubtreeDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(f, "DOM Subtree:")); writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data_and_primary_values(f, n), self.0, 1) fmt_subtree(f, &|f, n| fmt_with_data_and_primary_values(f, n), self.0, 1)
} }
} }
@ -230,12 +230,12 @@ fn fmt_subtree<F, N: TNode>(f: &mut fmt::Formatter, stringify: &F, n: N, indent:
where F: Fn(&mut fmt::Formatter, N) -> fmt::Result where F: Fn(&mut fmt::Formatter, N) -> fmt::Result
{ {
for _ in 0..indent { for _ in 0..indent {
try!(write!(f, " ")); write!(f, " ")?;
} }
try!(stringify(f, n)); stringify(f, n)?;
for kid in n.traversal_children() { for kid in n.traversal_children() {
try!(writeln!(f, "")); writeln!(f, "")?;
try!(fmt_subtree(f, stringify, kid, indent + 1)); fmt_subtree(f, stringify, kid, indent + 1)?;
} }
Ok(()) Ok(())

View file

@ -230,7 +230,7 @@ impl Resolution {
} }
fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
let (value, unit) = match try!(input.next()) { let (value, unit) = match input.next()? {
Token::Dimension { value, unit, .. } => { Token::Dimension { value, unit, .. } => {
(value, unit) (value, unit)
}, },
@ -462,9 +462,9 @@ impl Expression {
/// ``` /// ```
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> { -> Result<Self, ParseError<'i>> {
try!(input.expect_parenthesis_block()); input.expect_parenthesis_block()?;
input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let ident = try!(input.expect_ident()); let ident = input.expect_ident()?;
let mut flags = 0; let mut flags = 0;
let result = { let result = {

View file

@ -407,9 +407,9 @@ pub struct GeckoElement<'le>(pub &'le RawGeckoElement);
impl<'le> fmt::Debug for GeckoElement<'le> { impl<'le> fmt::Debug for GeckoElement<'le> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "<{}", self.get_local_name())); write!(f, "<{}", self.get_local_name())?;
if let Some(id) = self.get_id() { if let Some(id) = self.get_id() {
try!(write!(f, " id={}", id)); write!(f, " id={}", id)?;
} }
let mut first = true; let mut first = true;

View file

@ -235,7 +235,7 @@ impl fmt::Debug for WeakAtom {
impl fmt::Display for WeakAtom { impl fmt::Display for WeakAtom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
for c in self.chars() { for c in self.chars() {
try!(w.write_char(c.unwrap_or(char::REPLACEMENT_CHARACTER))) w.write_char(c.unwrap_or(char::REPLACEMENT_CHARACTER))?
} }
Ok(()) Ok(())
} }

View file

@ -207,11 +207,11 @@ pub fn serialize_comma_separated_list<W, T>(dest: &mut W,
return Ok(()); return Ok(());
} }
try!(list[0].to_css(dest)); list[0].to_css(dest)?;
for item in list.iter().skip(1) { for item in list.iter().skip(1) {
try!(write!(dest, ", ")); write!(dest, ", ")?;
try!(item.to_css(dest)); item.to_css(dest)?;
} }
Ok(()) Ok(())

View file

@ -144,20 +144,20 @@ impl WritingMode {
impl fmt::Display for WritingMode { impl fmt::Display for WritingMode {
fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> { fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
if self.is_vertical() { if self.is_vertical() {
try!(write!(formatter, "V")); write!(formatter, "V")?;
if self.is_vertical_lr() { if self.is_vertical_lr() {
try!(write!(formatter, " LR")); write!(formatter, " LR")?;
} else { } else {
try!(write!(formatter, " RL")); write!(formatter, " RL")?;
} }
if self.intersects(FLAG_SIDEWAYS) { if self.intersects(FLAG_SIDEWAYS) {
try!(write!(formatter, " Sideways")); write!(formatter, " Sideways")?;
} }
if self.intersects(FLAG_LINE_INVERTED) { if self.intersects(FLAG_LINE_INVERTED) {
try!(write!(formatter, " Inverted")); write!(formatter, " Inverted")?;
} }
} else { } else {
try!(write!(formatter, "H")); write!(formatter, "H")?;
} }
if self.is_bidi_ltr() { if self.is_bidi_ltr() {
write!(formatter, " LTR") write!(formatter, " LTR")

View file

@ -94,8 +94,8 @@ impl ToCss for MediaQuery {
where W: fmt::Write, where W: fmt::Write,
{ {
if let Some(qual) = self.qualifier { if let Some(qual) = self.qualifier {
try!(qual.to_css(dest)); qual.to_css(dest)?;
try!(write!(dest, " ")); write!(dest, " ")?;
} }
match self.media_type { match self.media_type {
@ -106,12 +106,12 @@ impl ToCss for MediaQuery {
// Otherwise, we'd serialize media queries like "(min-width: // Otherwise, we'd serialize media queries like "(min-width:
// 40px)" in "all (min-width: 40px)", which is unexpected. // 40px)" in "all (min-width: 40px)", which is unexpected.
if self.qualifier.is_some() || self.expressions.is_empty() { if self.qualifier.is_some() || self.expressions.is_empty() {
try!(write!(dest, "all")); write!(dest, "all")?;
} }
}, },
MediaQueryType::Known(MediaType::Screen) => try!(write!(dest, "screen")), MediaQueryType::Known(MediaType::Screen) => write!(dest, "screen")?,
MediaQueryType::Known(MediaType::Print) => try!(write!(dest, "print")), MediaQueryType::Known(MediaType::Print) => write!(dest, "print")?,
MediaQueryType::Unknown(ref desc) => try!(write!(dest, "{}", desc)), MediaQueryType::Unknown(ref desc) => write!(dest, "{}", desc)?,
} }
if self.expressions.is_empty() { if self.expressions.is_empty() {
@ -119,14 +119,14 @@ impl ToCss for MediaQuery {
} }
if self.media_type != MediaQueryType::All || self.qualifier.is_some() { if self.media_type != MediaQueryType::All || self.qualifier.is_some() {
try!(write!(dest, " and ")); write!(dest, " and ")?;
} }
try!(self.expressions[0].to_css(dest)); self.expressions[0].to_css(dest)?;
for expr in self.expressions.iter().skip(1) { for expr in self.expressions.iter().skip(1) {
try!(write!(dest, " and ")); write!(dest, " and ")?;
try!(expr.to_css(dest)); expr.to_css(dest)?;
} }
Ok(()) Ok(())
} }
@ -215,7 +215,7 @@ impl MediaQuery {
Ok(ident) => { Ok(ident) => {
let result: Result<_, ParseError> = MediaQueryType::parse(&*ident) let result: Result<_, ParseError> = MediaQueryType::parse(&*ident)
.map_err(|()| SelectorParseError::UnexpectedIdent(ident).into()); .map_err(|()| SelectorParseError::UnexpectedIdent(ident).into());
try!(result) result?
} }
Err(_) => { Err(_) => {
// Media type is only optional if qualifier is not specified. // Media type is only optional if qualifier is not specified.
@ -224,7 +224,7 @@ impl MediaQuery {
} }
// Without a media type, require at least one expression. // Without a media type, require at least one expression.
expressions.push(try!(Expression::parse(context, input))); expressions.push(Expression::parse(context, input)?);
MediaQueryType::All MediaQueryType::All
} }
@ -235,7 +235,7 @@ impl MediaQuery {
if input.try(|input| input.expect_ident_matching("and")).is_err() { if input.try(|input| input.expect_ident_matching("and")).is_err() {
return Ok(MediaQuery::new(qualifier, media_type, expressions)) return Ok(MediaQuery::new(qualifier, media_type, expressions))
} }
expressions.push(try!(Expression::parse(context, input))) expressions.push(Expression::parse(context, input)?)
} }
} }
} }

View file

@ -840,10 +840,10 @@ pub fn append_serialization<'a, W, I, N>(dest: &mut W,
I: Iterator<Item=&'a PropertyDeclaration>, I: Iterator<Item=&'a PropertyDeclaration>,
N: ToCss, N: ToCss,
{ {
try!(handle_first_serialization(dest, is_first_serialization)); handle_first_serialization(dest, is_first_serialization)?;
try!(property_name.to_css(dest)); property_name.to_css(dest)?;
try!(dest.write_char(':')); dest.write_char(':')?;
// for normal parsed values, add a space between key: and value // for normal parsed values, add a space between key: and value
match appendable_value { match appendable_value {
@ -863,10 +863,10 @@ pub fn append_serialization<'a, W, I, N>(dest: &mut W,
AppendableValue::DeclarationsForShorthand(..) => unreachable!(), AppendableValue::DeclarationsForShorthand(..) => unreachable!(),
} }
try!(append_declaration_value(dest, appendable_value)); append_declaration_value(dest, appendable_value)?;
if importance.important() { if importance.important() {
try!(dest.write_str(" !important")); dest.write_str(" !important")?;
} }
dest.write_char(';') dest.write_char(';')
@ -934,7 +934,7 @@ impl<'a, 'b, 'i> DeclarationParser<'i> for PropertyDeclarationParser<'a, 'b> {
fn parse_value<'t>(&mut self, name: CompactCowStr<'i>, input: &mut Parser<'i, 't>) fn parse_value<'t>(&mut self, name: CompactCowStr<'i>, input: &mut Parser<'i, 't>)
-> Result<Importance, ParseError<'i>> { -> Result<Importance, ParseError<'i>> {
let id = try!(PropertyId::parse(name)); let id = PropertyId::parse(name)?;
input.parse_until_before(Delimiter::Bang, |input| { input.parse_until_before(Delimiter::Bang, |input| {
PropertyDeclaration::parse_into(self.declarations, id, self.context, input) PropertyDeclaration::parse_into(self.declarations, id, self.context, input)
.map_err(|e| e.into()) .map_err(|e| e.into())

View file

@ -158,17 +158,17 @@
{ {
let mut iter = self.0.iter(); let mut iter = self.0.iter();
if let Some(val) = iter.next() { if let Some(val) = iter.next() {
try!(val.to_css(dest)); val.to_css(dest)?;
} else { } else {
% if allow_empty: % if allow_empty:
try!(dest.write_str("none")); dest.write_str("none")?;
% else: % else:
warn!("Found empty value for property ${name}"); warn!("Found empty value for property ${name}");
% endif % endif
} }
for i in iter { for i in iter {
try!(dest.write_str(", ")); dest.write_str(", ")?;
try!(i.to_css(dest)); i.to_css(dest)?;
} }
Ok(()) Ok(())
} }
@ -185,17 +185,17 @@
{ {
let mut iter = self.0.iter(); let mut iter = self.0.iter();
if let Some(val) = iter.next() { if let Some(val) = iter.next() {
try!(val.to_css(dest)); val.to_css(dest)?;
} else { } else {
% if allow_empty: % if allow_empty:
try!(dest.write_str("none")); dest.write_str("none")?;
% else: % else:
warn!("Found empty value for property ${name}"); warn!("Found empty value for property ${name}");
% endif % endif
} }
for i in iter { for i in iter {
try!(dest.write_str(", ")); dest.write_str(", ")?;
try!(i.to_css(dest)); i.to_css(dest)?;
} }
Ok(()) Ok(())
} }
@ -462,8 +462,8 @@
let var = input.seen_var_functions(); let var = input.seen_var_functions();
if specified.is_err() && var { if specified.is_err() && var {
input.reset(start); input.reset(start);
let (first_token_type, css) = try!( let (first_token_type, css) =
::custom_properties::parse_non_custom_with_var(input)); ::custom_properties::parse_non_custom_with_var(input)?;
return Ok(PropertyDeclaration::WithVariables(LonghandId::${property.camel_case}, return Ok(PropertyDeclaration::WithVariables(LonghandId::${property.camel_case},
Arc::new(UnparsedValue { Arc::new(UnparsedValue {
css: css.into_owned(), css: css.into_owned(),
@ -876,8 +876,8 @@
Ok(()) Ok(())
} else if var { } else if var {
input.reset(start); input.reset(start);
let (first_token_type, css) = try!( let (first_token_type, css) =
::custom_properties::parse_non_custom_with_var(input)); ::custom_properties::parse_non_custom_with_var(input)?;
let unparsed = Arc::new(UnparsedValue { let unparsed = Arc::new(UnparsedValue {
css: css.into_owned(), css: css.into_owned(),
first_token_type: first_token_type, first_token_type: first_token_type,

View file

@ -223,7 +223,7 @@ impl TransitionProperty {
/// Parse a transition-property value. /// Parse a transition-property value.
pub fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { pub fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
let ident = try!(input.expect_ident()); let ident = input.expect_ident()?;
let supported = match_ignore_ascii_case! { &ident, let supported = match_ignore_ascii_case! { &ident,
"all" => Ok(Some(TransitionProperty::All)), "all" => Ok(Some(TransitionProperty::All)),
% for prop in data.longhands + data.shorthands_except_all(): % for prop in data.longhands + data.shorthands_except_all():
@ -986,8 +986,8 @@ impl Animatable for Visibility {
impl<T: Animatable + Copy> Animatable for Size2D<T> { impl<T: Animatable + Copy> Animatable for Size2D<T> {
#[inline] #[inline]
fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> { fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
let width = try!(self.width.add_weighted(&other.width, self_portion, other_portion)); let width = self.width.add_weighted(&other.width, self_portion, other_portion)?;
let height = try!(self.height.add_weighted(&other.height, self_portion, other_portion)); let height = self.height.add_weighted(&other.height, self_portion, other_portion)?;
Ok(Size2D::new(width, height)) Ok(Size2D::new(width, height))
} }
@ -996,8 +996,8 @@ impl<T: Animatable + Copy> Animatable for Size2D<T> {
impl<T: Animatable + Copy> Animatable for Point2D<T> { impl<T: Animatable + Copy> Animatable for Point2D<T> {
#[inline] #[inline]
fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> { fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
let x = try!(self.x.add_weighted(&other.x, self_portion, other_portion)); let x = self.x.add_weighted(&other.x, self_portion, other_portion)?;
let y = try!(self.y.add_weighted(&other.y, self_portion, other_portion)); let y = self.y.add_weighted(&other.y, self_portion, other_portion)?;
Ok(Point2D::new(x, y)) Ok(Point2D::new(x, y))
} }
@ -1016,8 +1016,8 @@ impl Animatable for BorderCornerRadius {
#[inline] #[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> { fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
Ok(try!(self.0.width.compute_squared_distance(&other.0.width)) + Ok(self.0.width.compute_squared_distance(&other.0.width)? +
try!(self.0.height.compute_squared_distance(&other.0.height))) self.0.height.compute_squared_distance(&other.0.height)?)
} }
} }
@ -1487,10 +1487,8 @@ impl<H: Animatable, V: Animatable> Animatable for generic_position::Position<H,
#[inline] #[inline]
fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> { fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
Ok(generic_position::Position { Ok(generic_position::Position {
horizontal: try!(self.horizontal.add_weighted(&other.horizontal, horizontal: self.horizontal.add_weighted(&other.horizontal, self_portion, other_portion)?,
self_portion, other_portion)), vertical: self.vertical.add_weighted(&other.vertical, self_portion, other_portion)?,
vertical: try!(self.vertical.add_weighted(&other.vertical,
self_portion, other_portion)),
}) })
} }
@ -1509,8 +1507,8 @@ impl<H: Animatable, V: Animatable> Animatable for generic_position::Position<H,
#[inline] #[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> { fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
Ok(try!(self.horizontal.compute_squared_distance(&other.horizontal)) + Ok(self.horizontal.compute_squared_distance(&other.horizontal)? +
try!(self.vertical.compute_squared_distance(&other.vertical))) self.vertical.compute_squared_distance(&other.vertical)?)
} }
} }
@ -1523,10 +1521,10 @@ impl Animatable for ClipRect {
fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64)
-> Result<Self, ()> { -> Result<Self, ()> {
Ok(ClipRect { Ok(ClipRect {
top: try!(self.top.add_weighted(&other.top, self_portion, other_portion)), top: self.top.add_weighted(&other.top, self_portion, other_portion)?,
right: try!(self.right.add_weighted(&other.right, self_portion, other_portion)), right: self.right.add_weighted(&other.right, self_portion, other_portion)?,
bottom: try!(self.bottom.add_weighted(&other.bottom, self_portion, other_portion)), bottom: self.bottom.add_weighted(&other.bottom, self_portion, other_portion)?,
left: try!(self.left.add_weighted(&other.left, self_portion, other_portion)), left: self.left.add_weighted(&other.left, self_portion, other_portion)?,
}) })
} }
@ -1537,10 +1535,12 @@ impl Animatable for ClipRect {
#[inline] #[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> { fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
let list = [ try!(self.top.compute_distance(&other.top)), let list = [
try!(self.right.compute_distance(&other.right)), self.top.compute_distance(&other.top)?,
try!(self.bottom.compute_distance(&other.bottom)), self.right.compute_distance(&other.right)?,
try!(self.left.compute_distance(&other.left)) ]; self.bottom.compute_distance(&other.bottom)?,
self.left.compute_distance(&other.left)?
];
Ok(list.iter().fold(0.0f64, |sum, diff| sum + diff * diff)) Ok(list.iter().fold(0.0f64, |sum, diff| sum + diff * diff))
} }
} }
@ -1630,9 +1630,9 @@ fn add_weighted_with_initial_val<T: Animatable>(a: &T,
a_portion: f64, a_portion: f64,
b_portion: f64, b_portion: f64,
initial_val: &T) -> Result<T, ()> { initial_val: &T) -> Result<T, ()> {
let a = try!(a.add_weighted(&initial_val, 1.0, -1.0)); let a = a.add_weighted(&initial_val, 1.0, -1.0)?;
let b = try!(b.add_weighted(&initial_val, 1.0, -1.0)); let b = b.add_weighted(&initial_val, 1.0, -1.0)?;
let result = try!(a.add_weighted(&b, a_portion, b_portion)); let result = a.add_weighted(&b, a_portion, b_portion)?;
result.add_weighted(&initial_val, 1.0, 1.0) result.add_weighted(&initial_val, 1.0, 1.0)
} }
@ -1793,12 +1793,12 @@ pub struct MatrixDecomposed2D {
impl Animatable for InnerMatrix2D { impl Animatable for InnerMatrix2D {
fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> { fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
Ok(InnerMatrix2D { Ok(InnerMatrix2D {
m11: try!(add_weighted_with_initial_val(&self.m11, &other.m11, m11: add_weighted_with_initial_val(&self.m11, &other.m11,
self_portion, other_portion, &1.0)), self_portion, other_portion, &1.0)?,
m12: try!(self.m12.add_weighted(&other.m12, self_portion, other_portion)), m12: self.m12.add_weighted(&other.m12, self_portion, other_portion)?,
m21: try!(self.m21.add_weighted(&other.m21, self_portion, other_portion)), m21: self.m21.add_weighted(&other.m21, self_portion, other_portion)?,
m22: try!(add_weighted_with_initial_val(&self.m22, &other.m22, m22: add_weighted_with_initial_val(&self.m22, &other.m22,
self_portion, other_portion, &1.0)), self_portion, other_portion, &1.0)?,
}) })
} }
} }
@ -1806,8 +1806,8 @@ impl Animatable for InnerMatrix2D {
impl Animatable for Translate2D { impl Animatable for Translate2D {
fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> { fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
Ok(Translate2D( Ok(Translate2D(
try!(self.0.add_weighted(&other.0, self_portion, other_portion)), self.0.add_weighted(&other.0, self_portion, other_portion)?,
try!(self.1.add_weighted(&other.1, self_portion, other_portion)) self.1.add_weighted(&other.1, self_portion, other_portion)?,
)) ))
} }
} }
@ -1815,8 +1815,8 @@ impl Animatable for Translate2D {
impl Animatable for Scale2D { impl Animatable for Scale2D {
fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> { fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
Ok(Scale2D( Ok(Scale2D(
try!(add_weighted_with_initial_val(&self.0, &other.0, self_portion, other_portion, &1.0)), add_weighted_with_initial_val(&self.0, &other.0, self_portion, other_portion, &1.0)?,
try!(add_weighted_with_initial_val(&self.1, &other.1, self_portion, other_portion, &1.0)) add_weighted_with_initial_val(&self.1, &other.1, self_portion, other_portion, &1.0)?,
)) ))
} }
} }
@ -1853,11 +1853,10 @@ impl Animatable for MatrixDecomposed2D {
} }
// Interpolate all values. // Interpolate all values.
let translate = try!(self.translate.add_weighted(&other.translate, let translate = self.translate.add_weighted(&other.translate, self_portion, other_portion)?;
self_portion, other_portion)); let scale = scale.add_weighted(&other.scale, self_portion, other_portion)?;
let scale = try!(scale.add_weighted(&other.scale, self_portion, other_portion)); let angle = angle.add_weighted(&other_angle, self_portion, other_portion)?;
let angle = try!(angle.add_weighted(&other_angle, self_portion, other_portion)); let matrix = self.matrix.add_weighted(&other.matrix, self_portion, other_portion)?;
let matrix = try!(self.matrix.add_weighted(&other.matrix, self_portion, other_portion));
Ok(MatrixDecomposed2D { Ok(MatrixDecomposed2D {
translate: translate, translate: translate,
@ -1875,7 +1874,7 @@ impl Animatable for ComputedMatrix {
let decomposed_to = decompose_3d_matrix(*other); let decomposed_to = decompose_3d_matrix(*other);
match (decomposed_from, decomposed_to) { match (decomposed_from, decomposed_to) {
(Ok(from), Ok(to)) => { (Ok(from), Ok(to)) => {
let sum = try!(from.add_weighted(&to, self_portion, other_portion)); let sum = from.add_weighted(&to, self_portion, other_portion)?;
Ok(ComputedMatrix::from(sum)) Ok(ComputedMatrix::from(sum))
}, },
_ => { _ => {
@ -1886,8 +1885,7 @@ impl Animatable for ComputedMatrix {
} else { } else {
let decomposed_from = MatrixDecomposed2D::from(*self); let decomposed_from = MatrixDecomposed2D::from(*self);
let decomposed_to = MatrixDecomposed2D::from(*other); let decomposed_to = MatrixDecomposed2D::from(*other);
let sum = try!(decomposed_from.add_weighted(&decomposed_to, let sum = decomposed_from.add_weighted(&decomposed_to, self_portion, other_portion)?;
self_portion, other_portion));
Ok(ComputedMatrix::from(sum)) Ok(ComputedMatrix::from(sum))
} }
} }
@ -2228,9 +2226,9 @@ fn cross(row1: [f32; 3], row2: [f32; 3]) -> [f32; 3] {
impl Animatable for Translate3D { impl Animatable for Translate3D {
fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> { fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
Ok(Translate3D( Ok(Translate3D(
try!(self.0.add_weighted(&other.0, self_portion, other_portion)), self.0.add_weighted(&other.0, self_portion, other_portion)?,
try!(self.1.add_weighted(&other.1, self_portion, other_portion)), self.1.add_weighted(&other.1, self_portion, other_portion)?,
try!(self.2.add_weighted(&other.2, self_portion, other_portion)) self.2.add_weighted(&other.2, self_portion, other_portion)?,
)) ))
} }
} }
@ -2238,9 +2236,9 @@ impl Animatable for Translate3D {
impl Animatable for Scale3D { impl Animatable for Scale3D {
fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> { fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
Ok(Scale3D( Ok(Scale3D(
try!(add_weighted_with_initial_val(&self.0, &other.0, self_portion, other_portion, &1.0)), add_weighted_with_initial_val(&self.0, &other.0, self_portion, other_portion, &1.0)?,
try!(add_weighted_with_initial_val(&self.1, &other.1, self_portion, other_portion, &1.0)), add_weighted_with_initial_val(&self.1, &other.1, self_portion, other_portion, &1.0)?,
try!(add_weighted_with_initial_val(&self.2, &other.2, self_portion, other_portion, &1.0)) add_weighted_with_initial_val(&self.2, &other.2, self_portion, other_portion, &1.0)?,
)) ))
} }
} }
@ -2248,9 +2246,9 @@ impl Animatable for Scale3D {
impl Animatable for Skew { impl Animatable for Skew {
fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> { fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
Ok(Skew( Ok(Skew(
try!(self.0.add_weighted(&other.0, self_portion, other_portion)), self.0.add_weighted(&other.0, self_portion, other_portion)?,
try!(self.1.add_weighted(&other.1, self_portion, other_portion)), self.1.add_weighted(&other.1, self_portion, other_portion)?,
try!(self.2.add_weighted(&other.2, self_portion, other_portion)) self.2.add_weighted(&other.2, self_portion, other_portion)?,
)) ))
} }
} }
@ -2258,10 +2256,10 @@ impl Animatable for Skew {
impl Animatable for Perspective { impl Animatable for Perspective {
fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> { fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
Ok(Perspective( Ok(Perspective(
try!(self.0.add_weighted(&other.0, self_portion, other_portion)), self.0.add_weighted(&other.0, self_portion, other_portion)?,
try!(self.1.add_weighted(&other.1, self_portion, other_portion)), self.1.add_weighted(&other.1, self_portion, other_portion)?,
try!(self.2.add_weighted(&other.2, self_portion, other_portion)), self.2.add_weighted(&other.2, self_portion, other_portion)?,
try!(add_weighted_with_initial_val(&self.3, &other.3, self_portion, other_portion, &1.0)) add_weighted_with_initial_val(&self.3, &other.3, self_portion, other_portion, &1.0)?,
)) ))
} }
} }
@ -2277,12 +2275,10 @@ impl Animatable for MatrixDecomposed3D {
let mut sum = *self; let mut sum = *self;
// Add translate, scale, skew and perspective components. // Add translate, scale, skew and perspective components.
sum.translate = try!(self.translate.add_weighted(&other.translate, sum.translate = self.translate.add_weighted(&other.translate, self_portion, other_portion)?;
self_portion, other_portion)); sum.scale = self.scale.add_weighted(&other.scale, self_portion, other_portion)?;
sum.scale = try!(self.scale.add_weighted(&other.scale, self_portion, other_portion)); sum.skew = self.skew.add_weighted(&other.skew, self_portion, other_portion)?;
sum.skew = try!(self.skew.add_weighted(&other.skew, self_portion, other_portion)); sum.perspective = self.perspective.add_weighted(&other.perspective, self_portion, other_portion)?;
sum.perspective = try!(self.perspective.add_weighted(&other.perspective,
self_portion, other_portion));
// Add quaternions using spherical linear interpolation (Slerp). // Add quaternions using spherical linear interpolation (Slerp).
// //
@ -2734,25 +2730,22 @@ impl Animatable for IntermediateRGBA {
#[inline] #[inline]
fn add_weighted(&self, other: &IntermediateRGBA, self_portion: f64, other_portion: f64) fn add_weighted(&self, other: &IntermediateRGBA, self_portion: f64, other_portion: f64)
-> Result<Self, ()> { -> Result<Self, ()> {
let mut alpha = try!(self.alpha.add_weighted(&other.alpha, self_portion, other_portion)); let mut alpha = self.alpha.add_weighted(&other.alpha, self_portion, other_portion)?;
if alpha <= 0. { if alpha <= 0. {
// Ideally we should return color value that only alpha component is // Ideally we should return color value that only alpha component is
// 0, but this is what current gecko does. // 0, but this is what current gecko does.
Ok(IntermediateRGBA::transparent()) Ok(IntermediateRGBA::transparent())
} else { } else {
alpha = alpha.min(1.); alpha = alpha.min(1.);
let red = try!((self.red * self.alpha) let red = (self.red * self.alpha).add_weighted(
.add_weighted(&(other.red * other.alpha), &(other.red * other.alpha), self_portion, other_portion
self_portion, other_portion)) )? * 1. / alpha;
* 1. / alpha; let green = (self.green * self.alpha).add_weighted(
let green = try!((self.green * self.alpha) &(other.green * other.alpha), self_portion, other_portion
.add_weighted(&(other.green * other.alpha), )? * 1. / alpha;
self_portion, other_portion)) let blue = (self.blue * self.alpha).add_weighted(
* 1. / alpha; &(other.blue * other.alpha), self_portion, other_portion
let blue = try!((self.blue * self.alpha) )? * 1. / alpha;
.add_weighted(&(other.blue * other.alpha),
self_portion, other_portion))
* 1. / alpha;
Ok(IntermediateRGBA::new(red, green, blue, alpha)) Ok(IntermediateRGBA::new(red, green, blue, alpha))
} }
} }
@ -3093,13 +3086,11 @@ impl Animatable for IntermediateShadow {
return Err(()); return Err(());
} }
let x = try!(self.offset_x.add_weighted(&other.offset_x, self_portion, other_portion)); let x = self.offset_x.add_weighted(&other.offset_x, self_portion, other_portion)?;
let y = try!(self.offset_y.add_weighted(&other.offset_y, self_portion, other_portion)); let y = self.offset_y.add_weighted(&other.offset_y, self_portion, other_portion)?;
let color = try!(self.color.add_weighted(&other.color, self_portion, other_portion)); let color = self.color.add_weighted(&other.color, self_portion, other_portion)?;
let blur = try!(self.blur_radius.add_weighted(&other.blur_radius, let blur = self.blur_radius.add_weighted(&other.blur_radius, self_portion, other_portion)?;
self_portion, other_portion)); let spread = self.spread_radius.add_weighted(&other.spread_radius, self_portion, other_portion)?;
let spread = try!(self.spread_radius.add_weighted(&other.spread_radius,
self_portion, other_portion));
Ok(IntermediateShadow { Ok(IntermediateShadow {
offset_x: x, offset_x: x,
@ -3121,11 +3112,12 @@ impl Animatable for IntermediateShadow {
if self.inset != other.inset { if self.inset != other.inset {
return Err(()); return Err(());
} }
let list = [ try!(self.offset_x.compute_distance(&other.offset_x)), let list = [
try!(self.offset_y.compute_distance(&other.offset_y)), self.offset_x.compute_distance(&other.offset_x)?,
try!(self.blur_radius.compute_distance(&other.blur_radius)), self.offset_y.compute_distance(&other.offset_y)?,
try!(self.color.compute_distance(&other.color)), self.blur_radius.compute_distance(&other.blur_radius)?,
try!(self.spread_radius.compute_distance(&other.spread_radius)), self.color.compute_distance(&other.color)?,
self.spread_radius.compute_distance(&other.spread_radius)?,
]; ];
Ok(list.iter().fold(0.0f64, |sum, diff| sum + diff * diff)) Ok(list.iter().fold(0.0f64, |sum, diff| sum + diff * diff))
} }
@ -3155,8 +3147,9 @@ impl Animatable for IntermediateShadowList {
for i in 0..max_len { for i in 0..max_len {
let shadow = match (self.0.get(i), other.0.get(i)) { let shadow = match (self.0.get(i), other.0.get(i)) {
(Some(shadow), Some(other)) => (Some(shadow), Some(other)) => {
try!(shadow.add_weighted(other, self_portion, other_portion)), shadow.add_weighted(other, self_portion, other_portion)?
}
(Some(shadow), None) => { (Some(shadow), None) => {
zero.inset = shadow.inset; zero.inset = shadow.inset;
shadow.add_weighted(&zero, self_portion, other_portion).unwrap() shadow.add_weighted(&zero, self_portion, other_portion).unwrap()

View file

@ -66,10 +66,10 @@ ${helpers.predefined_type("background-image", "ImageLayer",
(RepeatKeyword::Repeat, RepeatKeyword::NoRepeat) => dest.write_str("repeat-x"), (RepeatKeyword::Repeat, RepeatKeyword::NoRepeat) => dest.write_str("repeat-x"),
(RepeatKeyword::NoRepeat, RepeatKeyword::Repeat) => dest.write_str("repeat-y"), (RepeatKeyword::NoRepeat, RepeatKeyword::Repeat) => dest.write_str("repeat-y"),
(horizontal, vertical) => { (horizontal, vertical) => {
try!(horizontal.to_css(dest)); horizontal.to_css(dest)?;
if horizontal != vertical { if horizontal != vertical {
try!(dest.write_str(" ")); dest.write_str(" ")?;
try!(vertical.to_css(dest)); vertical.to_css(dest)?;
} }
Ok(()) Ok(())
}, },
@ -82,10 +82,10 @@ ${helpers.predefined_type("background-image", "ImageLayer",
SpecifiedValue::RepeatX => dest.write_str("repeat-x"), SpecifiedValue::RepeatX => dest.write_str("repeat-x"),
SpecifiedValue::RepeatY => dest.write_str("repeat-y"), SpecifiedValue::RepeatY => dest.write_str("repeat-y"),
SpecifiedValue::Other(horizontal, vertical) => { SpecifiedValue::Other(horizontal, vertical) => {
try!(horizontal.to_css(dest)); horizontal.to_css(dest)?;
if let Some(vertical) = vertical { if let Some(vertical) = vertical {
try!(dest.write_str(" ")); dest.write_str(" ")?;
try!(vertical.to_css(dest)); vertical.to_css(dest)?;
} }
Ok(()) Ok(())
} }
@ -138,7 +138,7 @@ ${helpers.predefined_type("background-image", "ImageLayer",
}).or_else(|()| { }).or_else(|()| {
let horizontal: Result<_, ParseError> = RepeatKeyword::from_ident(&ident) let horizontal: Result<_, ParseError> = RepeatKeyword::from_ident(&ident)
.map_err(|()| SelectorParseError::UnexpectedIdent(ident).into()); .map_err(|()| SelectorParseError::UnexpectedIdent(ident).into());
let horizontal = try!(horizontal); let horizontal = horizontal?;
let vertical = input.try(RepeatKeyword::parse).ok(); let vertical = input.try(RepeatKeyword::parse).ok();
Ok(SpecifiedValue::Other(horizontal, vertical)) Ok(SpecifiedValue::Other(horizontal, vertical))
}) })

View file

@ -91,10 +91,10 @@ ${helpers.gecko_keyword_conversion(Keyword('border-style',
let mut first = true; let mut first = true;
for ref color in vec { for ref color in vec {
if !first { if !first {
try!(dest.write_str(" ")); dest.write_str(" ")?;
} }
first = false; first = false;
try!(color.to_css(dest)) color.to_css(dest)?
} }
Ok(()) Ok(())
} }
@ -110,10 +110,10 @@ ${helpers.gecko_keyword_conversion(Keyword('border-style',
let mut first = true; let mut first = true;
for ref color in vec { for ref color in vec {
if !first { if !first {
try!(dest.write_str(" ")); dest.write_str(" ")?;
} }
first = false; first = false;
try!(color.to_css(dest)) color.to_css(dest)?
} }
Ok(()) Ok(())
} }
@ -240,10 +240,10 @@ ${helpers.predefined_type("border-image-outset", "LengthOrNumberRect",
impl ToCss for SpecifiedValue { impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
try!(self.0.to_css(dest)); self.0.to_css(dest)?;
if let Some(second) = self.1 { if let Some(second) = self.1 {
try!(dest.write_str(" ")); dest.write_str(" ")?;
try!(second.to_css(dest)); second.to_css(dest)?;
} }
Ok(()) Ok(())
} }
@ -274,7 +274,7 @@ ${helpers.predefined_type("border-image-outset", "LengthOrNumberRect",
pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> { -> Result<SpecifiedValue, ParseError<'i>> {
let first = try!(RepeatKeyword::parse(input)); let first = RepeatKeyword::parse(input)?;
let second = input.try(RepeatKeyword::parse).ok(); let second = input.try(RepeatKeyword::parse).ok();
Ok(SpecifiedValue(first, second)) Ok(SpecifiedValue(first, second))

View file

@ -567,7 +567,7 @@ ${helpers.predefined_type("animation-timing-function",
return Ok(SpecifiedValue::Infinite) return Ok(SpecifiedValue::Infinite)
} }
let number = try!(input.expect_number()); let number = input.expect_number()?;
if number < 0.0 { if number < 0.0 {
return Err(StyleParseError::UnspecifiedError.into()); return Err(StyleParseError::UnspecifiedError.into());
} }
@ -936,10 +936,10 @@ ${helpers.predefined_type("scroll-snap-coordinate",
let mut first = true; let mut first = true;
for operation in &self.0 { for operation in &self.0 {
if !first { if !first {
try!(dest.write_str(" ")); dest.write_str(" ")?;
} }
first = false; first = false;
try!(operation.to_css(dest)) operation.to_css(dest)?
} }
Ok(()) Ok(())
} }
@ -966,12 +966,12 @@ ${helpers.predefined_type("scroll-snap-coordinate",
let valid_fn = match_ignore_ascii_case! { let valid_fn = match_ignore_ascii_case! {
&name, &name,
"matrix" => { "matrix" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
// Standard matrix parsing. // Standard matrix parsing.
if !prefixed { if !prefixed {
let values = try!(input.parse_comma_separated(|input| { let values = input.parse_comma_separated(|input| {
specified::parse_number(context, input) specified::parse_number(context, input)
})); })?;
if values.len() != 6 { if values.len() != 6 {
return Err(StyleParseError::UnspecifiedError.into()) return Err(StyleParseError::UnspecifiedError.into())
} }
@ -1018,13 +1018,13 @@ ${helpers.predefined_type("scroll-snap-coordinate",
f: lengths[1].clone(), f: lengths[1].clone(),
}); });
Ok(true) Ok(true)
})) })?
}, },
"matrix3d" => { "matrix3d" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
// Standard matrix3d parsing. // Standard matrix3d parsing.
if !prefixed { if !prefixed {
let values = try!(input.parse_comma_separated(|i| specified::parse_number(context, i))); let values = input.parse_comma_separated(|i| specified::parse_number(context, i))?;
if values.len() != 16 { if values.len() != 16 {
return Err(StyleParseError::UnspecifiedError.into()) return Err(StyleParseError::UnspecifiedError.into())
} }
@ -1073,170 +1073,170 @@ ${helpers.predefined_type("scroll-snap-coordinate",
m44: values[12] m44: values[12]
}); });
Ok(true) Ok(true)
})) })?
}, },
"translate" => { "translate" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let sx = try!(specified::LengthOrPercentage::parse(context, input)); let sx = specified::LengthOrPercentage::parse(context, input)?;
if input.try(|input| input.expect_comma()).is_ok() { if input.try(|input| input.expect_comma()).is_ok() {
let sy = try!(specified::LengthOrPercentage::parse(context, input)); let sy = specified::LengthOrPercentage::parse(context, input)?;
result.push(SpecifiedOperation::Translate(sx, Some(sy))); result.push(SpecifiedOperation::Translate(sx, Some(sy)));
} else { } else {
result.push(SpecifiedOperation::Translate(sx, None)); result.push(SpecifiedOperation::Translate(sx, None));
} }
Ok(true) Ok(true)
})) })?
}, },
"translatex" => { "translatex" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let tx = try!(specified::LengthOrPercentage::parse(context, input)); let tx = specified::LengthOrPercentage::parse(context, input)?;
result.push(SpecifiedOperation::TranslateX(tx)); result.push(SpecifiedOperation::TranslateX(tx));
Ok(true) Ok(true)
})) })?
}, },
"translatey" => { "translatey" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let ty = try!(specified::LengthOrPercentage::parse(context, input)); let ty = specified::LengthOrPercentage::parse(context, input)?;
result.push(SpecifiedOperation::TranslateY(ty)); result.push(SpecifiedOperation::TranslateY(ty));
Ok(true) Ok(true)
})) })?
}, },
"translatez" => { "translatez" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let tz = try!(specified::Length::parse(context, input)); let tz = specified::Length::parse(context, input)?;
result.push(SpecifiedOperation::TranslateZ(tz)); result.push(SpecifiedOperation::TranslateZ(tz));
Ok(true) Ok(true)
})) })?
}, },
"translate3d" => { "translate3d" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let tx = try!(specified::LengthOrPercentage::parse(context, input)); let tx = specified::LengthOrPercentage::parse(context, input)?;
try!(input.expect_comma()); input.expect_comma()?;
let ty = try!(specified::LengthOrPercentage::parse(context, input)); let ty = specified::LengthOrPercentage::parse(context, input)?;
try!(input.expect_comma()); input.expect_comma()?;
let tz = try!(specified::Length::parse(context, input)); let tz = specified::Length::parse(context, input)?;
result.push(SpecifiedOperation::Translate3D(tx, ty, tz)); result.push(SpecifiedOperation::Translate3D(tx, ty, tz));
Ok(true) Ok(true)
})) })?
}, },
"scale" => { "scale" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let sx = try!(specified::parse_number(context, input)); let sx = specified::parse_number(context, input)?;
if input.try(|input| input.expect_comma()).is_ok() { if input.try(|input| input.expect_comma()).is_ok() {
let sy = try!(specified::parse_number(context, input)); let sy = specified::parse_number(context, input)?;
result.push(SpecifiedOperation::Scale(sx, Some(sy))); result.push(SpecifiedOperation::Scale(sx, Some(sy)));
} else { } else {
result.push(SpecifiedOperation::Scale(sx, None)); result.push(SpecifiedOperation::Scale(sx, None));
} }
Ok(true) Ok(true)
})) })?
}, },
"scalex" => { "scalex" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let sx = try!(specified::parse_number(context, input)); let sx = specified::parse_number(context, input)?;
result.push(SpecifiedOperation::ScaleX(sx)); result.push(SpecifiedOperation::ScaleX(sx));
Ok(true) Ok(true)
})) })?
}, },
"scaley" => { "scaley" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let sy = try!(specified::parse_number(context, input)); let sy = specified::parse_number(context, input)?;
result.push(SpecifiedOperation::ScaleY(sy)); result.push(SpecifiedOperation::ScaleY(sy));
Ok(true) Ok(true)
})) })?
}, },
"scalez" => { "scalez" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let sz = try!(specified::parse_number(context, input)); let sz = specified::parse_number(context, input)?;
result.push(SpecifiedOperation::ScaleZ(sz)); result.push(SpecifiedOperation::ScaleZ(sz));
Ok(true) Ok(true)
})) })?
}, },
"scale3d" => { "scale3d" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let sx = try!(specified::parse_number(context, input)); let sx = specified::parse_number(context, input)?;
try!(input.expect_comma()); input.expect_comma()?;
let sy = try!(specified::parse_number(context, input)); let sy = specified::parse_number(context, input)?;
try!(input.expect_comma()); input.expect_comma()?;
let sz = try!(specified::parse_number(context, input)); let sz = specified::parse_number(context, input)?;
result.push(SpecifiedOperation::Scale3D(sx, sy, sz)); result.push(SpecifiedOperation::Scale3D(sx, sy, sz));
Ok(true) Ok(true)
})) })?
}, },
"rotate" => { "rotate" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let theta = try!(specified::Angle::parse_with_unitless(context, input)); let theta = specified::Angle::parse_with_unitless(context, input)?;
result.push(SpecifiedOperation::Rotate(theta)); result.push(SpecifiedOperation::Rotate(theta));
Ok(true) Ok(true)
})) })?
}, },
"rotatex" => { "rotatex" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let theta = try!(specified::Angle::parse_with_unitless(context, input)); let theta = specified::Angle::parse_with_unitless(context, input)?;
result.push(SpecifiedOperation::RotateX(theta)); result.push(SpecifiedOperation::RotateX(theta));
Ok(true) Ok(true)
})) })?
}, },
"rotatey" => { "rotatey" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let theta = try!(specified::Angle::parse_with_unitless(context, input)); let theta = specified::Angle::parse_with_unitless(context, input)?;
result.push(SpecifiedOperation::RotateY(theta)); result.push(SpecifiedOperation::RotateY(theta));
Ok(true) Ok(true)
})) })?
}, },
"rotatez" => { "rotatez" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let theta = try!(specified::Angle::parse_with_unitless(context, input)); let theta = specified::Angle::parse_with_unitless(context, input)?;
result.push(SpecifiedOperation::RotateZ(theta)); result.push(SpecifiedOperation::RotateZ(theta));
Ok(true) Ok(true)
})) })?
}, },
"rotate3d" => { "rotate3d" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let ax = try!(specified::parse_number(context, input)); let ax = specified::parse_number(context, input)?;
try!(input.expect_comma()); input.expect_comma()?;
let ay = try!(specified::parse_number(context, input)); let ay = specified::parse_number(context, input)?;
try!(input.expect_comma()); input.expect_comma()?;
let az = try!(specified::parse_number(context, input)); let az = specified::parse_number(context, input)?;
try!(input.expect_comma()); input.expect_comma()?;
let theta = try!(specified::Angle::parse_with_unitless(context, input)); let theta = specified::Angle::parse_with_unitless(context, input)?;
// TODO(gw): Check the axis can be normalized!! // TODO(gw): Check the axis can be normalized!!
result.push(SpecifiedOperation::Rotate3D(ax, ay, az, theta)); result.push(SpecifiedOperation::Rotate3D(ax, ay, az, theta));
Ok(true) Ok(true)
})) })?
}, },
"skew" => { "skew" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let theta_x = try!(specified::Angle::parse_with_unitless(context, input)); let theta_x = specified::Angle::parse_with_unitless(context, input)?;
if input.try(|input| input.expect_comma()).is_ok() { if input.try(|input| input.expect_comma()).is_ok() {
let theta_y = try!(specified::Angle::parse_with_unitless(context, input)); let theta_y = specified::Angle::parse_with_unitless(context, input)?;
result.push(SpecifiedOperation::Skew(theta_x, Some(theta_y))); result.push(SpecifiedOperation::Skew(theta_x, Some(theta_y)));
} else { } else {
result.push(SpecifiedOperation::Skew(theta_x, None)); result.push(SpecifiedOperation::Skew(theta_x, None));
} }
Ok(true) Ok(true)
})) })?
}, },
"skewx" => { "skewx" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let theta_x = try!(specified::Angle::parse_with_unitless(context, input)); let theta_x = specified::Angle::parse_with_unitless(context, input)?;
result.push(SpecifiedOperation::SkewX(theta_x)); result.push(SpecifiedOperation::SkewX(theta_x));
Ok(true) Ok(true)
})) })?
}, },
"skewy" => { "skewy" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let theta_y = try!(specified::Angle::parse_with_unitless(context, input)); let theta_y = specified::Angle::parse_with_unitless(context, input)?;
result.push(SpecifiedOperation::SkewY(theta_y)); result.push(SpecifiedOperation::SkewY(theta_y));
Ok(true) Ok(true)
})) })?
}, },
"perspective" => { "perspective" => {
try!(input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let d = try!(specified::Length::parse_non_negative(context, input)); let d = specified::Length::parse_non_negative(context, input)?;
result.push(SpecifiedOperation::Perspective(d)); result.push(SpecifiedOperation::Perspective(d));
Ok(true) Ok(true)
})) })?
}, },
_ => false _ => false
}; };
@ -1757,10 +1757,10 @@ ${helpers.predefined_type("transform-origin",
($ident:ident => $str:expr) => { ($ident:ident => $str:expr) => {
if self.contains($ident) { if self.contains($ident) {
if has_any { if has_any {
try!(dest.write_str(" ")); dest.write_str(" ")?;
} }
has_any = true; has_any = true;
try!(dest.write_str($str)); dest.write_str($str)?;
} }
} }
} }

View file

@ -71,18 +71,18 @@
match *self { match *self {
ContentItem::String(ref s) => s.to_css(dest), ContentItem::String(ref s) => s.to_css(dest),
ContentItem::Counter(ref s, ref counter_style) => { ContentItem::Counter(ref s, ref counter_style) => {
try!(dest.write_str("counter(")); dest.write_str("counter(")?;
try!(cssparser::serialize_identifier(&**s, dest)); cssparser::serialize_identifier(&**s, dest)?;
try!(dest.write_str(", ")); dest.write_str(", ")?;
try!(counter_style.to_css(dest)); counter_style.to_css(dest)?;
dest.write_str(")") dest.write_str(")")
} }
ContentItem::Counters(ref s, ref separator, ref counter_style) => { ContentItem::Counters(ref s, ref separator, ref counter_style) => {
try!(dest.write_str("counters(")); dest.write_str("counters(")?;
try!(cssparser::serialize_identifier(&**s, dest)); cssparser::serialize_identifier(&**s, dest)?;
try!(dest.write_str(", ")); dest.write_str(", ")?;
separator.to_css(dest)?; separator.to_css(dest)?;
try!(dest.write_str(", ")); dest.write_str(", ")?;
counter_style.to_css(dest)?; counter_style.to_css(dest)?;
dest.write_str(")") dest.write_str(")")
} }
@ -121,10 +121,10 @@
% endif % endif
T::Items(ref content) => { T::Items(ref content) => {
let mut iter = content.iter(); let mut iter = content.iter();
try!(iter.next().unwrap().to_css(dest)); iter.next().unwrap().to_css(dest)?;
for c in iter { for c in iter {
try!(dest.write_str(" ")); dest.write_str(" ")?;
try!(c.to_css(dest)); c.to_css(dest)?;
} }
Ok(()) Ok(())
} }
@ -186,14 +186,14 @@
Ok(Token::Function(name)) => { Ok(Token::Function(name)) => {
let result = match_ignore_ascii_case! { &name, let result = match_ignore_ascii_case! { &name,
"counter" => Some(input.parse_nested_block(|input| { "counter" => Some(input.parse_nested_block(|input| {
let name = try!(input.expect_ident()).into_owned(); let name = input.expect_ident()?.into_owned();
let style = parse_counter_style(context, input); let style = parse_counter_style(context, input);
Ok(ContentItem::Counter(name, style)) Ok(ContentItem::Counter(name, style))
})), })),
"counters" => Some(input.parse_nested_block(|input| { "counters" => Some(input.parse_nested_block(|input| {
let name = try!(input.expect_ident()).into_owned(); let name = input.expect_ident()?.into_owned();
try!(input.expect_comma()); input.expect_comma()?;
let separator = try!(input.expect_string()).into_owned(); let separator = input.expect_string()?.into_owned();
let style = parse_counter_style(context, input); let style = parse_counter_style(context, input);
Ok(ContentItem::Counters(name, separator, style)) Ok(ContentItem::Counters(name, separator, style))
})), })),
@ -205,7 +205,7 @@
_ => None _ => None
}; };
match result { match result {
Some(result) => content.push(try!(result)), Some(result) => content.push(result?),
None => return Err(StyleParseError::UnexpectedFunction(name).into()) None => return Err(StyleParseError::UnexpectedFunction(name).into())
} }
} }

View file

@ -159,14 +159,14 @@ ${helpers.predefined_type("clip",
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut iter = self.filters.iter(); let mut iter = self.filters.iter();
if let Some(filter) = iter.next() { if let Some(filter) = iter.next() {
try!(filter.to_css(dest)); filter.to_css(dest)?;
} else { } else {
try!(dest.write_str("none")); dest.write_str("none")?;
return Ok(()) return Ok(())
} }
for filter in iter { for filter in iter {
try!(dest.write_str(" ")); dest.write_str(" ")?;
try!(filter.to_css(dest)); filter.to_css(dest)?;
} }
Ok(()) Ok(())
} }
@ -176,14 +176,14 @@ ${helpers.predefined_type("clip",
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut iter = self.0.iter(); let mut iter = self.0.iter();
if let Some(filter) = iter.next() { if let Some(filter) = iter.next() {
try!(filter.to_css(dest)); filter.to_css(dest)?;
} else { } else {
try!(dest.write_str("none")); dest.write_str("none")?;
return Ok(()) return Ok(())
} }
for filter in iter { for filter in iter {
try!(dest.write_str(" ")); dest.write_str(" ")?;
try!(filter.to_css(dest)); filter.to_css(dest)?;
} }
Ok(()) Ok(())
} }
@ -193,22 +193,22 @@ ${helpers.predefined_type("clip",
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self { match *self {
computed_value::Filter::Blur(ref value) => { computed_value::Filter::Blur(ref value) => {
try!(dest.write_str("blur(")); dest.write_str("blur(")?;
try!(value.to_css(dest)); value.to_css(dest)?;
try!(dest.write_str(")")); dest.write_str(")")?;
} }
computed_value::Filter::Brightness(value) => try!(write!(dest, "brightness({})", value)), computed_value::Filter::Brightness(value) => write!(dest, "brightness({})", value)?,
computed_value::Filter::Contrast(value) => try!(write!(dest, "contrast({})", value)), computed_value::Filter::Contrast(value) => write!(dest, "contrast({})", value)?,
computed_value::Filter::Grayscale(value) => try!(write!(dest, "grayscale({})", value)), computed_value::Filter::Grayscale(value) => write!(dest, "grayscale({})", value)?,
computed_value::Filter::HueRotate(value) => { computed_value::Filter::HueRotate(value) => {
try!(dest.write_str("hue-rotate(")); dest.write_str("hue-rotate(")?;
try!(value.to_css(dest)); value.to_css(dest)?;
try!(dest.write_str(")")); dest.write_str(")")?;
} }
computed_value::Filter::Invert(value) => try!(write!(dest, "invert({})", value)), computed_value::Filter::Invert(value) => write!(dest, "invert({})", value)?,
computed_value::Filter::Opacity(value) => try!(write!(dest, "opacity({})", value)), computed_value::Filter::Opacity(value) => write!(dest, "opacity({})", value)?,
computed_value::Filter::Saturate(value) => try!(write!(dest, "saturate({})", value)), computed_value::Filter::Saturate(value) => write!(dest, "saturate({})", value)?,
computed_value::Filter::Sepia(value) => try!(write!(dest, "sepia({})", value)), computed_value::Filter::Sepia(value) => write!(dest, "sepia({})", value)?,
% if product == "gecko": % if product == "gecko":
computed_value::Filter::DropShadow(shadow) => { computed_value::Filter::DropShadow(shadow) => {
dest.write_str("drop-shadow(")?; dest.write_str("drop-shadow(")?;
@ -228,22 +228,22 @@ ${helpers.predefined_type("clip",
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self { match *self {
SpecifiedFilter::Blur(ref value) => { SpecifiedFilter::Blur(ref value) => {
try!(dest.write_str("blur(")); dest.write_str("blur(")?;
try!(value.to_css(dest)); value.to_css(dest)?;
try!(dest.write_str(")")); dest.write_str(")")?;
} }
SpecifiedFilter::Brightness(value) => try!(write!(dest, "brightness({})", value)), SpecifiedFilter::Brightness(value) => write!(dest, "brightness({})", value)?,
SpecifiedFilter::Contrast(value) => try!(write!(dest, "contrast({})", value)), SpecifiedFilter::Contrast(value) => write!(dest, "contrast({})", value)?,
SpecifiedFilter::Grayscale(value) => try!(write!(dest, "grayscale({})", value)), SpecifiedFilter::Grayscale(value) => write!(dest, "grayscale({})", value)?,
SpecifiedFilter::HueRotate(value) => { SpecifiedFilter::HueRotate(value) => {
try!(dest.write_str("hue-rotate(")); dest.write_str("hue-rotate(")?;
try!(value.to_css(dest)); value.to_css(dest)?;
try!(dest.write_str(")")); dest.write_str(")")?;
} }
SpecifiedFilter::Invert(value) => try!(write!(dest, "invert({})", value)), SpecifiedFilter::Invert(value) => write!(dest, "invert({})", value)?,
SpecifiedFilter::Opacity(value) => try!(write!(dest, "opacity({})", value)), SpecifiedFilter::Opacity(value) => write!(dest, "opacity({})", value)?,
SpecifiedFilter::Saturate(value) => try!(write!(dest, "saturate({})", value)), SpecifiedFilter::Saturate(value) => write!(dest, "saturate({})", value)?,
SpecifiedFilter::Sepia(value) => try!(write!(dest, "sepia({})", value)), SpecifiedFilter::Sepia(value) => write!(dest, "sepia({})", value)?,
% if product == "gecko": % if product == "gecko":
SpecifiedFilter::DropShadow(ref shadow) => { SpecifiedFilter::DropShadow(ref shadow) => {
dest.write_str("drop-shadow(")?; dest.write_str("drop-shadow(")?;
@ -277,7 +277,7 @@ ${helpers.predefined_type("clip",
} else } else
% endif % endif
if let Ok(function_name) = input.try(|input| input.expect_function()) { if let Ok(function_name) = input.try(|input| input.expect_function()) {
filters.push(try!(input.parse_nested_block(|input| { filters.push(input.parse_nested_block(|input| {
match_ignore_ascii_case! { &function_name, match_ignore_ascii_case! { &function_name,
"blur" => specified::Length::parse_non_negative(context, input).map(SpecifiedFilter::Blur), "blur" => specified::Length::parse_non_negative(context, input).map(SpecifiedFilter::Blur),
"brightness" => parse_factor(input).map(SpecifiedFilter::Brightness), "brightness" => parse_factor(input).map(SpecifiedFilter::Brightness),
@ -294,7 +294,7 @@ ${helpers.predefined_type("clip",
% endif % endif
_ => Err(StyleParseError::UnexpectedFunction(function_name.clone()).into()) _ => Err(StyleParseError::UnexpectedFunction(function_name.clone()).into())
} }
}))); })?);
} else if filters.is_empty() { } else if filters.is_empty() {
return Err(StyleParseError::UnspecifiedError.into()) return Err(StyleParseError::UnspecifiedError.into())
} else { } else {

View file

@ -160,7 +160,7 @@ macro_rules! impl_gecko_keyword_from_trait {
quoted: true, quoted: true,
})) }))
} }
let first_ident = try!(input.expect_ident()); let first_ident = input.expect_ident()?;
// FIXME(bholley): The fast thing to do here would be to look up the // FIXME(bholley): The fast thing to do here would be to look up the
// string (as lowercase) in the static atoms table. We don't have an // string (as lowercase) in the static atoms table. We don't have an
@ -271,10 +271,10 @@ macro_rules! impl_gecko_keyword_from_trait {
impl ToCss for T { impl ToCss for T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut iter = self.0.iter(); let mut iter = self.0.iter();
try!(iter.next().unwrap().to_css(dest)); iter.next().unwrap().to_css(dest)?;
for family in iter { for family in iter {
try!(dest.write_str(", ")); dest.write_str(", ")?;
try!(family.to_css(dest)); family.to_css(dest)?;
} }
Ok(()) Ok(())
} }
@ -1125,8 +1125,7 @@ ${helpers.single_keyword_system("font-variant-caps",
-> Result<Self, ()> { -> Result<Self, ()> {
match (*self, *other) { match (*self, *other) {
(T::Number(ref number), T::Number(ref other)) => (T::Number(ref number), T::Number(ref other)) =>
Ok(T::Number(try!(number.add_weighted(other, Ok(T::Number(number.add_weighted(other, self_portion, other_portion)?)),
self_portion, other_portion)))),
_ => Err(()), _ => Err(()),
} }
} }
@ -1161,7 +1160,7 @@ ${helpers.single_keyword_system("font-variant-caps",
return Ok(SpecifiedValue::None); return Ok(SpecifiedValue::None);
} }
Ok(SpecifiedValue::Number(try!(Number::parse_non_negative(context, input)))) Ok(SpecifiedValue::Number(Number::parse_non_negative(context, input)?))
} }
</%helpers:longhand> </%helpers:longhand>
@ -1327,10 +1326,10 @@ ${helpers.single_keyword_system("font-kerning",
($ident:ident => $str:expr) => { ($ident:ident => $str:expr) => {
if self.intersects($ident) { if self.intersects($ident) {
if has_any { if has_any {
try!(dest.write_str(" ")); dest.write_str(" ")?;
} }
has_any = true; has_any = true;
try!(dest.write_str($str)); dest.write_str($str)?;
} }
} }
} }
@ -1473,10 +1472,10 @@ macro_rules! exclusive_value {
($ident:ident => $str:expr) => { ($ident:ident => $str:expr) => {
if self.intersects($ident) { if self.intersects($ident) {
if has_any { if has_any {
try!(dest.write_str(" ")); dest.write_str(" ")?;
} }
has_any = true; has_any = true;
try!(dest.write_str($str)); dest.write_str($str)?;
} }
} }
} }
@ -1620,10 +1619,10 @@ macro_rules! exclusive_value {
($ident:ident => $str:expr) => { ($ident:ident => $str:expr) => {
if self.intersects($ident) { if self.intersects($ident) {
if has_any { if has_any {
try!(dest.write_str(" ")); dest.write_str(" ")?;
} }
has_any = true; has_any = true;
try!(dest.write_str($str)); dest.write_str($str)?;
} }
} }
} }
@ -1776,10 +1775,10 @@ macro_rules! exclusive_value {
($ident:ident => $str:expr) => { ($ident:ident => $str:expr) => {
if self.intersects($ident) { if self.intersects($ident) {
if has_any { if has_any {
try!(dest.write_str(" ")); dest.write_str(" ")?;
} }
has_any = true; has_any = true;
try!(dest.write_str($str)); dest.write_str($str)?;
} }
} }
} }

View file

@ -82,7 +82,7 @@ ${helpers.single_keyword("image-rendering",
impl ToCss for SpecifiedValue { impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if let Some(angle) = self.angle { if let Some(angle) = self.angle {
try!(angle.to_css(dest)); angle.to_css(dest)?;
if self.flipped { if self.flipped {
dest.write_str(" flip") dest.write_str(" flip")
} else { } else {
@ -163,9 +163,9 @@ ${helpers.single_keyword("image-rendering",
match *self { match *self {
computed_value::T::FromImage => dest.write_str("from-image"), computed_value::T::FromImage => dest.write_str("from-image"),
computed_value::T::AngleWithFlipped(angle, flipped) => { computed_value::T::AngleWithFlipped(angle, flipped) => {
try!(angle.to_css(dest)); angle.to_css(dest)?;
if flipped { if flipped {
try!(dest.write_str(" flip")); dest.write_str(" flip")?;
} }
Ok(()) Ok(())
}, },

View file

@ -44,10 +44,10 @@ ${helpers.single_keyword("caption-side", "top bottom",
fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64)
-> Result<Self, ()> { -> Result<Self, ()> {
Ok(T { Ok(T {
horizontal: try!(self.horizontal.add_weighted(&other.horizontal, horizontal: self.horizontal.add_weighted(&other.horizontal,
self_portion, other_portion)), self_portion, other_portion)?,
vertical: try!(self.vertical.add_weighted(&other.vertical, vertical: self.vertical.add_weighted(&other.vertical,
self_portion, other_portion)), self_portion, other_portion)?,
}) })
} }
@ -58,8 +58,8 @@ ${helpers.single_keyword("caption-side", "top bottom",
#[inline] #[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> { fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
Ok(try!(self.horizontal.compute_squared_distance(&other.horizontal)) + Ok(self.horizontal.compute_squared_distance(&other.horizontal)? +
try!(self.vertical.compute_squared_distance(&other.vertical))) self.vertical.compute_squared_distance(&other.vertical)?)
} }
} }
} }
@ -83,9 +83,9 @@ ${helpers.single_keyword("caption-side", "top bottom",
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write, where W: fmt::Write,
{ {
try!(self.horizontal.to_css(dest)); self.horizontal.to_css(dest)?;
if let Some(vertical) = self.vertical.as_ref() { if let Some(vertical) = self.vertical.as_ref() {
try!(dest.write_str(" ")); dest.write_str(" ")?;
vertical.to_css(dest)?; vertical.to_css(dest)?;
} }
Ok(()) Ok(())

View file

@ -470,16 +470,16 @@ ${helpers.predefined_type("word-spacing",
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if let Some(fill) = self.fill() { if let Some(fill) = self.fill() {
if fill { if fill {
try!(dest.write_str("filled")); dest.write_str("filled")?;
} else { } else {
try!(dest.write_str("open")); dest.write_str("open")?;
} }
} }
if let Some(shape) = self.shape() { if let Some(shape) = self.shape() {
if self.fill().is_some() { if self.fill().is_some() {
try!(dest.write_str(" ")); dest.write_str(" ")?;
} }
try!(shape.to_css(dest)); shape.to_css(dest)?;
} }
Ok(()) Ok(())
} }
@ -487,11 +487,11 @@ ${helpers.predefined_type("word-spacing",
impl ToCss for computed_value::KeywordValue { impl ToCss for computed_value::KeywordValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if self.fill { if self.fill {
try!(dest.write_str("filled")); dest.write_str("filled")?;
} else { } else {
try!(dest.write_str("open")); dest.write_str("open")?;
} }
try!(dest.write_str(" ")); dest.write_str(" ")?;
self.shape.to_css(dest) self.shape.to_css(dest)
} }
} }
@ -643,11 +643,11 @@ ${helpers.predefined_type("word-spacing",
pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> { -> Result<SpecifiedValue, ParseError<'i>> {
if let Ok(horizontal) = input.try(|input| HorizontalWritingModeValue::parse(input)) { if let Ok(horizontal) = input.try(|input| HorizontalWritingModeValue::parse(input)) {
let vertical = try!(VerticalWritingModeValue::parse(input)); let vertical = VerticalWritingModeValue::parse(input)?;
Ok(SpecifiedValue(horizontal, vertical)) Ok(SpecifiedValue(horizontal, vertical))
} else { } else {
let vertical = try!(VerticalWritingModeValue::parse(input)); let vertical = VerticalWritingModeValue::parse(input)?;
let horizontal = try!(HorizontalWritingModeValue::parse(input)); let horizontal = HorizontalWritingModeValue::parse(input)?;
Ok(SpecifiedValue(horizontal, vertical)) Ok(SpecifiedValue(horizontal, vertical))
} }
} }

View file

@ -52,12 +52,12 @@
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
impl ToCss for Image { impl ToCss for Image {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
try!(self.url.to_css(dest)); self.url.to_css(dest)?;
if let Some((x, y)) = self.hotspot { if let Some((x, y)) = self.hotspot {
try!(dest.write_str(" ")); dest.write_str(" ")?;
try!(x.to_css(dest)); x.to_css(dest)?;
try!(dest.write_str(" ")); dest.write_str(" ")?;
try!(y.to_css(dest)); y.to_css(dest)?;
} }
Ok(()) Ok(())
} }
@ -67,8 +67,8 @@
impl ToCss for T { impl ToCss for T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
for url in &self.images { for url in &self.images {
try!(url.to_css(dest)); url.to_css(dest)?;
try!(dest.write_str(", ")); dest.write_str(", ")?;
} }
self.keyword.to_css(dest) self.keyword.to_css(dest)
} }
@ -95,7 +95,7 @@
-> Result<computed_value::Keyword, ParseError<'i>> { -> Result<computed_value::Keyword, ParseError<'i>> {
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
use style_traits::cursor::Cursor; use style_traits::cursor::Cursor;
let ident = try!(input.expect_ident()); let ident = input.expect_ident()?;
if ident.eq_ignore_ascii_case("auto") { if ident.eq_ignore_ascii_case("auto") {
Ok(computed_value::Keyword::Auto) Ok(computed_value::Keyword::Auto)
} else { } else {
@ -110,9 +110,9 @@
fn parse_image<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) fn parse_image<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<computed_value::Image, ParseError<'i>> { -> Result<computed_value::Image, ParseError<'i>> {
Ok(computed_value::Image { Ok(computed_value::Image {
url: try!(SpecifiedUrl::parse(context, input)), url: SpecifiedUrl::parse(context, input)?,
hotspot: match input.try(|input| input.expect_number()) { hotspot: match input.try(|input| input.expect_number()) {
Ok(number) => Some((number, try!(input.expect_number()))), Ok(number) => Some((number, input.expect_number()?)),
Err(_) => None, Err(_) => None,
}, },
}) })
@ -137,12 +137,12 @@
} }
Err(_) => break, Err(_) => break,
} }
try!(input.expect_comma()); input.expect_comma()?;
} }
Ok(computed_value::T { Ok(computed_value::T {
images: images, images: images,
keyword: try!(computed_value::Keyword::parse(context, input)), keyword: computed_value::Keyword::parse(context, input)?,
}) })
} }
</%helpers:longhand> </%helpers:longhand>

View file

@ -57,11 +57,11 @@
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if self.sides_are_logical { if self.sides_are_logical {
assert!(self.first == Side::Clip); assert!(self.first == Side::Clip);
try!(self.second.to_css(dest)); self.second.to_css(dest)?;
} else { } else {
try!(self.first.to_css(dest)); self.first.to_css(dest)?;
try!(dest.write_str(" ")); dest.write_str(" ")?;
try!(self.second.to_css(dest)); self.second.to_css(dest)?;
} }
Ok(()) Ok(())
} }
@ -133,10 +133,10 @@
impl ToCss for SpecifiedValue { impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
try!(self.first.to_css(dest)); self.first.to_css(dest)?;
if let Some(ref second) = self.second { if let Some(ref second) = self.second {
try!(dest.write_str(" ")); dest.write_str(" ")?;
try!(second.to_css(dest)); second.to_css(dest)?;
} }
Ok(()) Ok(())
} }

View file

@ -78,7 +78,7 @@ ${helpers.single_keyword("-moz-window-shadow", "none default menu tooltip sheet"
pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> { -> Result<SpecifiedValue, ParseError<'i>> {
match try!(input.expect_integer()) { match input.expect_integer()? {
0 => Ok(computed_value::T(false)), 0 => Ok(computed_value::T(false)),
1 => Ok(computed_value::T(true)), 1 => Ok(computed_value::T(true)),
_ => Err(StyleParseError::UnspecifiedError.into()), _ => Err(StyleParseError::UnspecifiedError.into()),

View file

@ -234,8 +234,8 @@ pub mod shorthands {
while let Ok(_) = input.next() {} // Look for var() while let Ok(_) = input.next() {} // Look for var()
if input.seen_var_functions() { if input.seen_var_functions() {
input.reset(start); input.reset(start);
let (first_token_type, css) = try!( let (first_token_type, css) =
::custom_properties::parse_non_custom_with_var(input)); ::custom_properties::parse_non_custom_with_var(input)?;
declarations.all_shorthand = AllShorthand::WithVariables(Arc::new(UnparsedValue { declarations.all_shorthand = AllShorthand::WithVariables(Arc::new(UnparsedValue {
css: css.into_owned(), css: css.into_owned(),
first_token_type: first_token_type, first_token_type: first_token_type,
@ -1137,8 +1137,8 @@ impl HasViewportPercentage for PropertyDeclaration {
impl fmt::Debug for PropertyDeclaration { impl fmt::Debug for PropertyDeclaration {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(self.id().to_css(f)); self.id().to_css(f)?;
try!(f.write_str(": ")); f.write_str(": ")?;
self.to_css(f) self.to_css(f)
} }
} }

View file

@ -39,7 +39,7 @@
% for name in "image position_x position_y repeat size attachment origin clip".split(): % for name in "image position_x position_y repeat size attachment origin clip".split():
let mut background_${name} = background_${name}::SpecifiedValue(Vec::new()); let mut background_${name} = background_${name}::SpecifiedValue(Vec::new());
% endfor % endfor
try!(input.parse_comma_separated(|input| { input.parse_comma_separated(|input| {
// background-color can only be in the last element, so if it // background-color can only be in the last element, so if it
// is parsed anywhere before, the value is invalid. // is parsed anywhere before, the value is invalid.
if background_color.is_some() { if background_color.is_some() {
@ -62,7 +62,7 @@
// Parse background size, if applicable. // Parse background size, if applicable.
size = input.try(|input| { size = input.try(|input| {
try!(input.expect_delim('/')); input.expect_delim('/')?;
background_size::single_value::parse(context, input) background_size::single_value::parse(context, input)
}).ok(); }).ok();
@ -110,7 +110,7 @@
} else { } else {
Err(StyleParseError::UnspecifiedError.into()) Err(StyleParseError::UnspecifiedError.into())
} }
})); })?;
Ok(expanded! { Ok(expanded! {
background_color: background_color.unwrap_or(Color::transparent()), background_color: background_color.unwrap_or(Color::transparent()),
@ -148,37 +148,37 @@
% endfor % endfor
if i != 0 { if i != 0 {
try!(write!(dest, ", ")); write!(dest, ", ")?;
} }
if i == len - 1 { if i == len - 1 {
try!(self.background_color.to_css(dest)); self.background_color.to_css(dest)?;
try!(write!(dest, " ")); write!(dest, " ")?;
} }
try!(image.to_css(dest)); image.to_css(dest)?;
% for name in "repeat attachment".split(): % for name in "repeat attachment".split():
try!(write!(dest, " ")); write!(dest, " ")?;
try!(${name}.to_css(dest)); ${name}.to_css(dest)?;
% endfor % endfor
try!(write!(dest, " ")); write!(dest, " ")?;
Position { Position {
horizontal: position_x.clone(), horizontal: position_x.clone(),
vertical: position_y.clone() vertical: position_y.clone()
}.to_css(dest)?; }.to_css(dest)?;
if *size != background_size::single_value::get_initial_specified_value() { if *size != background_size::single_value::get_initial_specified_value() {
try!(write!(dest, " / ")); write!(dest, " / ")?;
try!(size.to_css(dest)); size.to_css(dest)?;
} }
if *origin != Origin::padding_box || *clip != Clip::border_box { if *origin != Origin::padding_box || *clip != Clip::border_box {
try!(write!(dest, " ")); write!(dest, " ")?;
try!(origin.to_css(dest)); origin.to_css(dest)?;
if *clip != From::from(*origin) { if *clip != From::from(*origin) {
try!(write!(dest, " ")); write!(dest, " ")?;
try!(clip.to_css(dest)); clip.to_css(dest)?;
} }
} }
} }

View file

@ -104,7 +104,7 @@ pub fn parse_border<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Longhands, ParseError<'i>> { -> Result<Longhands, ParseError<'i>> {
let (color, style, width) = try!(super::parse_border(context, input)); let (color, style, width) = super::parse_border(context, input)?;
Ok(expanded! { Ok(expanded! {
border_${to_rust_ident(side)}_color: color, border_${to_rust_ident(side)}_color: color,
border_${to_rust_ident(side)}_style: style, border_${to_rust_ident(side)}_style: style,
@ -146,7 +146,7 @@ pub fn parse_border<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
use properties::longhands::{border_image_outset, border_image_repeat, border_image_slice}; use properties::longhands::{border_image_outset, border_image_repeat, border_image_slice};
use properties::longhands::{border_image_source, border_image_width}; use properties::longhands::{border_image_source, border_image_width};
let (color, style, width) = try!(super::parse_border(context, input)); let (color, style, width) = super::parse_border(context, input)?;
Ok(expanded! { Ok(expanded! {
% for side in PHYSICAL_SIDES: % for side in PHYSICAL_SIDES:
border_${side}_color: color.clone(), border_${side}_color: color.clone(),
@ -214,7 +214,7 @@ pub fn parse_border<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Longhands, ParseError<'i>> { -> Result<Longhands, ParseError<'i>> {
let radii = try!(BorderRadius::parse(context, input)); let radii = BorderRadius::parse(context, input)?;
Ok(expanded! { Ok(expanded! {
border_top_left_radius: radii.top_left, border_top_left_radius: radii.top_left,
border_top_right_radius: radii.top_right, border_top_right_radius: radii.top_right,
@ -262,7 +262,7 @@ pub fn parse_border<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
slice = Some(value); slice = Some(value);
// Parse border image width and outset, if applicable. // Parse border image width and outset, if applicable.
let maybe_width_outset: Result<_, ParseError> = input.try(|input| { let maybe_width_outset: Result<_, ParseError> = input.try(|input| {
try!(input.expect_delim('/')); input.expect_delim('/')?;
// Parse border image width, if applicable. // Parse border image width, if applicable.
let w = input.try(|input| let w = input.try(|input|
@ -270,7 +270,7 @@ pub fn parse_border<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
// Parse border image outset if applicable. // Parse border image outset if applicable.
let o = input.try(|input| { let o = input.try(|input| {
try!(input.expect_delim('/')); input.expect_delim('/')?;
border_image_outset::parse(context, input) border_image_outset::parse(context, input)
}).ok(); }).ok();
if w.is_none() && o.is_none() { if w.is_none() && o.is_none() {
@ -313,7 +313,7 @@ pub fn parse_border<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
Err(StyleParseError::UnspecifiedError.into()) Err(StyleParseError::UnspecifiedError.into())
} }
}); });
try!(result); result?;
Ok(expanded! { Ok(expanded! {
% for name in "outset repeat slice source width".split(): % for name in "outset repeat slice source width".split():

View file

@ -135,7 +135,7 @@ macro_rules! try_parse_one {
% endfor % endfor
if input.try(|input| input.expect_ident_matching("none")).is_err() { if input.try(|input| input.expect_ident_matching("none")).is_err() {
let results = try!(input.parse_comma_separated(|i| parse_one_transition(context, i))); let results = input.parse_comma_separated(|i| parse_one_transition(context, i))?;
for result in results { for result in results {
% for prop in "property duration timing_function delay".split(): % for prop in "property duration timing_function delay".split():
${prop}s.push(result.transition_${prop}); ${prop}s.push(result.transition_${prop});
@ -257,7 +257,7 @@ macro_rules! try_parse_one {
let mut ${prop}s = vec![]; let mut ${prop}s = vec![];
% endfor % endfor
let results = try!(input.parse_comma_separated(|i| parse_one_animation(context, i))); let results = input.parse_comma_separated(|i| parse_one_animation(context, i))?;
for result in results.into_iter() { for result in results.into_iter() {
% for prop in props: % for prop in props:
${prop}s.push(result.animation_${prop}); ${prop}s.push(result.animation_${prop});
@ -289,7 +289,7 @@ macro_rules! try_parse_one {
for i in 0..len { for i in 0..len {
if i != 0 { if i != 0 {
try!(write!(dest, ", ")); write!(dest, ", ")?;
} }
% for name in props[1:]: % for name in props[1:]:
@ -310,7 +310,7 @@ macro_rules! try_parse_one {
pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Longhands, ParseError<'i>> { -> Result<Longhands, ParseError<'i>> {
let result = try!(scroll_snap_type_x::parse(context, input)); let result = scroll_snap_type_x::parse(context, input)?;
Ok(expanded! { Ok(expanded! {
scroll_snap_type_x: result, scroll_snap_type_x: result,
scroll_snap_type_y: result, scroll_snap_type_y: result,

View file

@ -89,7 +89,7 @@
continue continue
} }
} }
size = Some(try!(font_size::parse(context, input))); size = Some(font_size::parse(context, input)?);
break break
} }
#[inline] #[inline]
@ -101,7 +101,7 @@
return Err(StyleParseError::UnspecifiedError.into()) return Err(StyleParseError::UnspecifiedError.into())
} }
let line_height = if input.try(|input| input.expect_delim('/')).is_ok() { let line_height = if input.try(|input| input.expect_delim('/')).is_ok() {
Some(try!(LineHeight::parse(context, input))) Some(LineHeight::parse(context, input)?)
} else { } else {
None None
}; };

View file

@ -41,7 +41,7 @@
let mut mask_${name} = mask_${name}::SpecifiedValue(Vec::new()); let mut mask_${name} = mask_${name}::SpecifiedValue(Vec::new());
% endfor % endfor
try!(input.parse_comma_separated(|input| { input.parse_comma_separated(|input| {
% for name in "image mode position size repeat origin clip composite".split(): % for name in "image mode position size repeat origin clip composite".split():
let mut ${name} = None; let mut ${name} = None;
% endfor % endfor
@ -59,7 +59,7 @@
// Parse mask size, if applicable. // Parse mask size, if applicable.
size = input.try(|input| { size = input.try(|input| {
try!(input.expect_delim('/')); input.expect_delim('/')?;
mask_size::single_value::parse(context, input) mask_size::single_value::parse(context, input)
}).ok(); }).ok();
@ -106,7 +106,7 @@
} else { } else {
Err(StyleParseError::UnspecifiedError.into()) Err(StyleParseError::UnspecifiedError.into())
} }
})); })?;
Ok(expanded! { Ok(expanded! {
% for name in "image mode position_x position_y size repeat origin clip composite".split(): % for name in "image mode position_x position_y size repeat origin clip composite".split():

View file

@ -66,7 +66,7 @@
pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Longhands, ParseError<'i>> { -> Result<Longhands, ParseError<'i>> {
let radii = try!(BorderRadius::parse(context, input)); let radii = BorderRadius::parse(context, input)?;
Ok(expanded! { Ok(expanded! {
_moz_outline_radius_topleft: radii.top_left, _moz_outline_radius_topleft: radii.top_left,
_moz_outline_radius_topright: radii.top_right, _moz_outline_radius_topright: radii.top_right,

View file

@ -50,7 +50,7 @@
fn parse_flexibility<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) fn parse_flexibility<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<(Number, Option<Number>),ParseError<'i>> { -> Result<(Number, Option<Number>),ParseError<'i>> {
let grow = try!(Number::parse_non_negative(context, input)); let grow = Number::parse_non_negative(context, input)?;
let shrink = input.try(|i| Number::parse_non_negative(context, i)).ok(); let shrink = input.try(|i| Number::parse_non_negative(context, i)).ok();
Ok((grow, shrink)) Ok((grow, shrink))
} }

View file

@ -154,20 +154,20 @@ impl Expression {
/// Only supports width and width ranges for now. /// Only supports width and width ranges for now.
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> { -> Result<Self, ParseError<'i>> {
try!(input.expect_parenthesis_block()); input.expect_parenthesis_block()?;
input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let name = try!(input.expect_ident()); let name = input.expect_ident()?;
try!(input.expect_colon()); input.expect_colon()?;
// TODO: Handle other media features // TODO: Handle other media features
Ok(Expression(match_ignore_ascii_case! { &name, Ok(Expression(match_ignore_ascii_case! { &name,
"min-width" => { "min-width" => {
ExpressionKind::Width(Range::Min(try!(specified::Length::parse_non_negative(context, input)))) ExpressionKind::Width(Range::Min(specified::Length::parse_non_negative(context, input)?))
}, },
"max-width" => { "max-width" => {
ExpressionKind::Width(Range::Max(try!(specified::Length::parse_non_negative(context, input)))) ExpressionKind::Width(Range::Max(specified::Length::parse_non_negative(context, input)?))
}, },
"width" => { "width" => {
ExpressionKind::Width(Range::Eq(try!(specified::Length::parse_non_negative(context, input)))) ExpressionKind::Width(Range::Eq(specified::Length::parse_non_negative(context, input)?))
}, },
_ => return Err(SelectorParseError::UnexpectedIdent(name.clone()).into()) _ => return Err(SelectorParseError::UnexpectedIdent(name.clone()).into())
})) }))
@ -195,14 +195,14 @@ impl ToCss for Expression {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write, where W: fmt::Write,
{ {
try!(write!(dest, "(")); write!(dest, "(")?;
let (mm, l) = match self.0 { let (mm, l) = match self.0 {
ExpressionKind::Width(Range::Min(ref l)) => ("min-", l), ExpressionKind::Width(Range::Min(ref l)) => ("min-", l),
ExpressionKind::Width(Range::Max(ref l)) => ("max-", l), ExpressionKind::Width(Range::Max(ref l)) => ("max-", l),
ExpressionKind::Width(Range::Eq(ref l)) => ("", l), ExpressionKind::Width(Range::Eq(ref l)) => ("", l),
}; };
try!(write!(dest, "{}width: ", mm)); write!(dest, "{}width: ", mm)?;
try!(l.to_css(dest)); l.to_css(dest)?;
write!(dest, ")") write!(dest, ")")
} }
} }

View file

@ -162,14 +162,14 @@ impl fmt::Display for ServoRestyleDamage {
for &(damage, damage_str) in &to_iter { for &(damage, damage_str) in &to_iter {
if self.contains(damage) { if self.contains(damage) {
if !first_elem { try!(write!(f, " | ")); } if !first_elem { write!(f, " | ")?; }
try!(write!(f, "{}", damage_str)); write!(f, "{}", damage_str)?;
first_elem = false; first_elem = false;
} }
} }
if first_elem { if first_elem {
try!(write!(f, "NoDamage")); write!(f, "NoDamage")?;
} }
Ok(()) Ok(())

Some files were not shown because too many files have changed in this diff Show more