file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
setup.py
#!/usr/bin/python import os import sys extra_opts = {'test_suite': 'tests'} extra_deps = [] extra_test_deps = [] if sys.version_info[:2] == (2, 6): extra_deps.append('argparse') extra_deps.append('simplejson') extra_test_deps.append('unittest2') extra_opts['test_suite'] = 'unittest2.collector' try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages try: with open('README.rst', 'r') as fd: extra_opts['long_description'] = fd.read() except IOError: pass # Install without README.rst setup( name='mongo-orchestration', version='0.4.dev0', author='MongoDB, Inc.', author_email='mongodb-user@googlegroups.com', description='Restful service for managing MongoDB servers', keywords=['mongo-orchestration', 'mongodb', 'mongo', 'rest', 'testing'], license="http://www.apache.org/licenses/LICENSE-2.0.html", platforms=['any'], url='https://github.com/10gen/mongo-orchestration', install_requires=['pymongo>=3.0.2', 'bottle>=0.12.7', 'CherryPy>=3.5.0'] + extra_deps, tests_require=['coverage>=3.5'] + extra_test_deps, packages=find_packages(exclude=('tests',)), package_data={ 'mongo_orchestration': [ os.path.join('configurations', config_dir, '*.json') for config_dir in ('servers', 'replica_sets', 'sharded_clusters') ] + [os.path.join('lib', 'client.pem')] }, classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: Implementation :: CPython" ], entry_points={ 'console_scripts': [ 'mongo-orchestration = mongo_orchestration.server:main' ]
}, **extra_opts )
random_line_split
1139f0b4c9e3_order_name_not_unique.py
"""order name not unique Revision ID: 1139f0b4c9e3 Revises: 220436d6dcdc Create Date: 2016-05-31 08:59:21.225314 """ # revision identifiers, used by Alembic. revision = '1139f0b4c9e3' down_revision = '220436d6dcdc' from alembic import op import sqlalchemy as sa def
(): ### commands auto generated by Alembic - please adjust! ### op.drop_constraint('orders_name_key', 'orders', type_='unique') ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_unique_constraint('orders_name_key', 'orders', ['name']) ### end Alembic commands ###
upgrade
identifier_name
1139f0b4c9e3_order_name_not_unique.py
"""order name not unique Revision ID: 1139f0b4c9e3 Revises: 220436d6dcdc Create Date: 2016-05-31 08:59:21.225314 """ # revision identifiers, used by Alembic. revision = '1139f0b4c9e3' down_revision = '220436d6dcdc' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ###
def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_unique_constraint('orders_name_key', 'orders', ['name']) ### end Alembic commands ###
op.drop_constraint('orders_name_key', 'orders', type_='unique') ### end Alembic commands ###
identifier_body
1139f0b4c9e3_order_name_not_unique.py
"""order name not unique Revision ID: 1139f0b4c9e3
# revision identifiers, used by Alembic. revision = '1139f0b4c9e3' down_revision = '220436d6dcdc' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_constraint('orders_name_key', 'orders', type_='unique') ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_unique_constraint('orders_name_key', 'orders', ['name']) ### end Alembic commands ###
Revises: 220436d6dcdc Create Date: 2016-05-31 08:59:21.225314 """
random_line_split
App.js
Kanboard.App = function() { this.controllers = {}; }; Kanboard.App.prototype.get = function(controller) { return this.controllers[controller]; }; Kanboard.App.prototype.execute = function() { for (var className in Kanboard) { if (className !== "App") { var controller = new Kanboard[className](this); this.controllers[className] = controller; if (typeof controller.execute === "function") { controller.execute(); } if (typeof controller.listen === "function") { controller.listen(); } if (typeof controller.focus === "function") { controller.focus(); } } } this.focus(); this.datePicker(); this.autoComplete(); this.tagAutoComplete(); }; Kanboard.App.prototype.focus = function() { // Auto-select input fields $(document).on('focus', '.auto-select', function() { $(this).select(); }); // Workaround for chrome $(document).on('mouseup', '.auto-select', function(e) { e.preventDefault(); }); }; Kanboard.App.prototype.datePicker = function() { var bodyElement = $("body"); var dateFormat = bodyElement.data("js-date-format"); var timeFormat = bodyElement.data("js-time-format"); var lang = bodyElement.data("js-lang"); $.datepicker.setDefaults($.datepicker.regional[lang]); $.timepicker.setDefaults($.timepicker.regional[lang]); // Datepicker $(".form-date").datepicker({ showOtherMonths: true, selectOtherMonths: true, dateFormat: dateFormat, constrainInput: false }); // Datetime picker $(".form-datetime").datetimepicker({ dateFormat: dateFormat, timeFormat: timeFormat, constrainInput: false }); }; Kanboard.App.prototype.tagAutoComplete = function() { $(".tag-autocomplete").select2({ tags: true }); }; Kanboard.App.prototype.autoComplete = function() { $(".autocomplete").each(function() { var input = $(this); var field = input.data("dst-field"); var extraFields = input.data("dst-extra-fields"); if ($('#form-' + field).val() === '')
input.autocomplete({ source: input.data("search-url"), minLength: 1, select: function(event, ui) { $("input[name=" + field + "]").val(ui.item.id); if (extraFields) { var fields = extraFields.split(','); for (var i = 0; i < fields.length; i++) { var fieldName = fields[i].trim(); $("input[name=" + fieldName + "]").val(ui.item[fieldName]); } } input.parent().find("button[type=submit]").removeAttr('disabled'); } }); }); }; Kanboard.App.prototype.hasId = function(id) { return !!document.getElementById(id); }; Kanboard.App.prototype.showLoadingIcon = function() { $("body").append('<span id="app-loading-icon">&nbsp;<i class="fa fa-spinner fa-spin"></i></span>'); }; Kanboard.App.prototype.hideLoadingIcon = function() { $("#app-loading-icon").remove(); };
{ input.parent().find("button[type=submit]").attr('disabled','disabled'); }
conditional_block
App.js
Kanboard.App = function() { this.controllers = {}; }; Kanboard.App.prototype.get = function(controller) { return this.controllers[controller]; }; Kanboard.App.prototype.execute = function() { for (var className in Kanboard) { if (className !== "App") { var controller = new Kanboard[className](this); this.controllers[className] = controller; if (typeof controller.execute === "function") { controller.execute(); } if (typeof controller.listen === "function") { controller.listen(); } if (typeof controller.focus === "function") { controller.focus(); } } } this.focus(); this.datePicker(); this.autoComplete(); this.tagAutoComplete(); }; Kanboard.App.prototype.focus = function() { // Auto-select input fields $(document).on('focus', '.auto-select', function() { $(this).select(); }); // Workaround for chrome $(document).on('mouseup', '.auto-select', function(e) { e.preventDefault(); }); }; Kanboard.App.prototype.datePicker = function() { var bodyElement = $("body"); var dateFormat = bodyElement.data("js-date-format"); var timeFormat = bodyElement.data("js-time-format"); var lang = bodyElement.data("js-lang"); $.datepicker.setDefaults($.datepicker.regional[lang]); $.timepicker.setDefaults($.timepicker.regional[lang]); // Datepicker $(".form-date").datepicker({ showOtherMonths: true, selectOtherMonths: true, dateFormat: dateFormat, constrainInput: false }); // Datetime picker $(".form-datetime").datetimepicker({ dateFormat: dateFormat, timeFormat: timeFormat, constrainInput: false }); }; Kanboard.App.prototype.tagAutoComplete = function() { $(".tag-autocomplete").select2({ tags: true }); }; Kanboard.App.prototype.autoComplete = function() { $(".autocomplete").each(function() { var input = $(this); var field = input.data("dst-field"); var extraFields = input.data("dst-extra-fields"); if ($('#form-' + field).val() === '') { input.parent().find("button[type=submit]").attr('disabled','disabled'); } input.autocomplete({ source: input.data("search-url"), minLength: 1, select: function(event, ui) { $("input[name=" + field + "]").val(ui.item.id); if (extraFields) { var fields = extraFields.split(','); for (var i = 0; i < fields.length; i++) { var fieldName = fields[i].trim(); $("input[name=" + fieldName + "]").val(ui.item[fieldName]); } } input.parent().find("button[type=submit]").removeAttr('disabled'); } }); }); }; Kanboard.App.prototype.hasId = function(id) { return !!document.getElementById(id); };
$("#app-loading-icon").remove(); };
Kanboard.App.prototype.showLoadingIcon = function() { $("body").append('<span id="app-loading-icon">&nbsp;<i class="fa fa-spinner fa-spin"></i></span>'); }; Kanboard.App.prototype.hideLoadingIcon = function() {
random_line_split
moon.py
from i3pystatus import IntervalModule, formatp import datetime import math import decimal import os from i3pystatus.core.util import TimeWrapper dec = decimal.Decimal class MoonPhase(IntervalModule): """ Available Formatters status: Allows for mapping of current moon phase - New Moon: - Waxing Crescent: - First Quarter: - Waxing Gibbous: - Full Moon: - Waning Gibbous: - Last Quarter: - Waning Crescent: """ settings = ( "format", ("status", "Current moon phase"), ("illum", "Percentage that is illuminated"), ("color", "Set color"), ) format = "{illum} {status}" interval = 60 * 60 * 2 # every 2 hours status = { "New Moon": "NM", "Waxing Crescent": "WaxCres", "First Quarter": "FQ", "Waxing Gibbous": "WaxGib", "Full Moon": "FM", "Waning Gibbous": "WanGib", "Last Quarter": "LQ", "Waning Cresent": "WanCres", } color = { "New Moon": "#00BDE5", "Waxing Crescent": "#138DD8", "First Quarter": "#265ECC", "Waxing Gibbous": "#392FBF", "Full Moon": "#4C00B3", "Waning Gibbous": "#871181", "Last Quarter": "#C32250", "Waning Crescent": "#FF341F", } def pos(now=None): days_in_second = 86400 now = datetime.datetime.now() difference = now - datetime.datetime(2001, 1, 1) days = dec(difference.days) + (dec(difference.seconds) / dec(days_in_second)) lunarCycle = dec("0.20439731") + (days * dec("0.03386319269")) return lunarCycle % dec(1) def current_phase(self): lunarCycle = self.pos() index = (lunarCycle * dec(8)) + dec("0.5") index = math.floor(index) return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent", }[int(index) & 7] def illum(self): phase = 0 lunarCycle = float(self.pos()) * 100 if lunarCycle > 50: phase = 100 - lunarCycle else:
return phase def run(self): fdict = { "status": self.status[self.current_phase()], "illum": self.illum(), } self.output = { "full_text": formatp(self.format, **fdict), "color": self.color[self.current_phase()], }
phase = lunarCycle * 2
conditional_block
moon.py
from i3pystatus import IntervalModule, formatp import datetime import math import decimal import os from i3pystatus.core.util import TimeWrapper dec = decimal.Decimal class MoonPhase(IntervalModule): """ Available Formatters status: Allows for mapping of current moon phase - New Moon: - Waxing Crescent: - First Quarter: - Waxing Gibbous: - Full Moon: - Waning Gibbous: - Last Quarter: - Waning Crescent: """ settings = ( "format", ("status", "Current moon phase"), ("illum", "Percentage that is illuminated"), ("color", "Set color"), ) format = "{illum} {status}" interval = 60 * 60 * 2 # every 2 hours status = { "New Moon": "NM", "Waxing Crescent": "WaxCres", "First Quarter": "FQ", "Waxing Gibbous": "WaxGib", "Full Moon": "FM", "Waning Gibbous": "WanGib", "Last Quarter": "LQ", "Waning Cresent": "WanCres", } color = { "New Moon": "#00BDE5", "Waxing Crescent": "#138DD8", "First Quarter": "#265ECC", "Waxing Gibbous": "#392FBF", "Full Moon": "#4C00B3", "Waning Gibbous": "#871181", "Last Quarter": "#C32250", "Waning Crescent": "#FF341F", } def pos(now=None): days_in_second = 86400 now = datetime.datetime.now() difference = now - datetime.datetime(2001, 1, 1) days = dec(difference.days) + (dec(difference.seconds) / dec(days_in_second)) lunarCycle = dec("0.20439731") + (days * dec("0.03386319269")) return lunarCycle % dec(1)
def current_phase(self): lunarCycle = self.pos() index = (lunarCycle * dec(8)) + dec("0.5") index = math.floor(index) return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent", }[int(index) & 7] def illum(self): phase = 0 lunarCycle = float(self.pos()) * 100 if lunarCycle > 50: phase = 100 - lunarCycle else: phase = lunarCycle * 2 return phase def run(self): fdict = { "status": self.status[self.current_phase()], "illum": self.illum(), } self.output = { "full_text": formatp(self.format, **fdict), "color": self.color[self.current_phase()], }
random_line_split
moon.py
from i3pystatus import IntervalModule, formatp import datetime import math import decimal import os from i3pystatus.core.util import TimeWrapper dec = decimal.Decimal class
(IntervalModule): """ Available Formatters status: Allows for mapping of current moon phase - New Moon: - Waxing Crescent: - First Quarter: - Waxing Gibbous: - Full Moon: - Waning Gibbous: - Last Quarter: - Waning Crescent: """ settings = ( "format", ("status", "Current moon phase"), ("illum", "Percentage that is illuminated"), ("color", "Set color"), ) format = "{illum} {status}" interval = 60 * 60 * 2 # every 2 hours status = { "New Moon": "NM", "Waxing Crescent": "WaxCres", "First Quarter": "FQ", "Waxing Gibbous": "WaxGib", "Full Moon": "FM", "Waning Gibbous": "WanGib", "Last Quarter": "LQ", "Waning Cresent": "WanCres", } color = { "New Moon": "#00BDE5", "Waxing Crescent": "#138DD8", "First Quarter": "#265ECC", "Waxing Gibbous": "#392FBF", "Full Moon": "#4C00B3", "Waning Gibbous": "#871181", "Last Quarter": "#C32250", "Waning Crescent": "#FF341F", } def pos(now=None): days_in_second = 86400 now = datetime.datetime.now() difference = now - datetime.datetime(2001, 1, 1) days = dec(difference.days) + (dec(difference.seconds) / dec(days_in_second)) lunarCycle = dec("0.20439731") + (days * dec("0.03386319269")) return lunarCycle % dec(1) def current_phase(self): lunarCycle = self.pos() index = (lunarCycle * dec(8)) + dec("0.5") index = math.floor(index) return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent", }[int(index) & 7] def illum(self): phase = 0 lunarCycle = float(self.pos()) * 100 if lunarCycle > 50: phase = 100 - lunarCycle else: phase = lunarCycle * 2 return phase def run(self): fdict = { "status": self.status[self.current_phase()], "illum": self.illum(), } self.output = { "full_text": formatp(self.format, **fdict), "color": self.color[self.current_phase()], }
MoonPhase
identifier_name
moon.py
from i3pystatus import IntervalModule, formatp import datetime import math import decimal import os from i3pystatus.core.util import TimeWrapper dec = decimal.Decimal class MoonPhase(IntervalModule): """ Available Formatters status: Allows for mapping of current moon phase - New Moon: - Waxing Crescent: - First Quarter: - Waxing Gibbous: - Full Moon: - Waning Gibbous: - Last Quarter: - Waning Crescent: """ settings = ( "format", ("status", "Current moon phase"), ("illum", "Percentage that is illuminated"), ("color", "Set color"), ) format = "{illum} {status}" interval = 60 * 60 * 2 # every 2 hours status = { "New Moon": "NM", "Waxing Crescent": "WaxCres", "First Quarter": "FQ", "Waxing Gibbous": "WaxGib", "Full Moon": "FM", "Waning Gibbous": "WanGib", "Last Quarter": "LQ", "Waning Cresent": "WanCres", } color = { "New Moon": "#00BDE5", "Waxing Crescent": "#138DD8", "First Quarter": "#265ECC", "Waxing Gibbous": "#392FBF", "Full Moon": "#4C00B3", "Waning Gibbous": "#871181", "Last Quarter": "#C32250", "Waning Crescent": "#FF341F", } def pos(now=None):
def current_phase(self): lunarCycle = self.pos() index = (lunarCycle * dec(8)) + dec("0.5") index = math.floor(index) return { 0: "New Moon", 1: "Waxing Crescent", 2: "First Quarter", 3: "Waxing Gibbous", 4: "Full Moon", 5: "Waning Gibbous", 6: "Last Quarter", 7: "Waning Crescent", }[int(index) & 7] def illum(self): phase = 0 lunarCycle = float(self.pos()) * 100 if lunarCycle > 50: phase = 100 - lunarCycle else: phase = lunarCycle * 2 return phase def run(self): fdict = { "status": self.status[self.current_phase()], "illum": self.illum(), } self.output = { "full_text": formatp(self.format, **fdict), "color": self.color[self.current_phase()], }
days_in_second = 86400 now = datetime.datetime.now() difference = now - datetime.datetime(2001, 1, 1) days = dec(difference.days) + (dec(difference.seconds) / dec(days_in_second)) lunarCycle = dec("0.20439731") + (days * dec("0.03386319269")) return lunarCycle % dec(1)
identifier_body
test_directoryscanner.py
import unittest from os import path from API.directoryscanner import find_runs_in_directory path_to_module = path.abspath(path.dirname(__file__)) class TestDirectoryScanner(unittest.TestCase): def test_sample_names_spaces(self): runs = find_runs_in_directory(path.join(path_to_module, "sample-names-with-spaces")) self.assertEqual(1, len(runs)) samples = runs[0].sample_list self.assertEqual(3, len(samples)) for sample in samples: self.assertEqual(sample.get_id(), sample.get_id().strip()) def test_single_end(self): runs = find_runs_in_directory(path.join(path_to_module, "single_end")) self.assertEqual(1, len(runs)) self.assertEqual("SINGLE_END", runs[0].metadata["layoutType"]) samples = runs[0].sample_list self.assertEqual(3, len(samples)) for sample in samples: self.assertFalse(sample.is_paired_end()) def test_completed_upload(self):
def test_find_sample_sheet_name_variations(self): runs = find_runs_in_directory(path.join(path_to_module, "sample-sheet-name-variations")) self.assertEqual(1, len(runs))
runs = find_runs_in_directory(path.join(path_to_module, "completed")) self.assertEqual(0, len(runs))
identifier_body
test_directoryscanner.py
import unittest from os import path from API.directoryscanner import find_runs_in_directory path_to_module = path.abspath(path.dirname(__file__)) class TestDirectoryScanner(unittest.TestCase): def test_sample_names_spaces(self): runs = find_runs_in_directory(path.join(path_to_module, "sample-names-with-spaces")) self.assertEqual(1, len(runs)) samples = runs[0].sample_list self.assertEqual(3, len(samples)) for sample in samples: self.assertEqual(sample.get_id(), sample.get_id().strip()) def test_single_end(self): runs = find_runs_in_directory(path.join(path_to_module, "single_end")) self.assertEqual(1, len(runs)) self.assertEqual("SINGLE_END", runs[0].metadata["layoutType"]) samples = runs[0].sample_list self.assertEqual(3, len(samples)) for sample in samples: self.assertFalse(sample.is_paired_end()) def test_completed_upload(self): runs = find_runs_in_directory(path.join(path_to_module, "completed")) self.assertEqual(0, len(runs)) def
(self): runs = find_runs_in_directory(path.join(path_to_module, "sample-sheet-name-variations")) self.assertEqual(1, len(runs))
test_find_sample_sheet_name_variations
identifier_name
test_directoryscanner.py
import unittest from os import path from API.directoryscanner import find_runs_in_directory path_to_module = path.abspath(path.dirname(__file__)) class TestDirectoryScanner(unittest.TestCase): def test_sample_names_spaces(self): runs = find_runs_in_directory(path.join(path_to_module, "sample-names-with-spaces")) self.assertEqual(1, len(runs)) samples = runs[0].sample_list self.assertEqual(3, len(samples)) for sample in samples:
def test_single_end(self): runs = find_runs_in_directory(path.join(path_to_module, "single_end")) self.assertEqual(1, len(runs)) self.assertEqual("SINGLE_END", runs[0].metadata["layoutType"]) samples = runs[0].sample_list self.assertEqual(3, len(samples)) for sample in samples: self.assertFalse(sample.is_paired_end()) def test_completed_upload(self): runs = find_runs_in_directory(path.join(path_to_module, "completed")) self.assertEqual(0, len(runs)) def test_find_sample_sheet_name_variations(self): runs = find_runs_in_directory(path.join(path_to_module, "sample-sheet-name-variations")) self.assertEqual(1, len(runs))
self.assertEqual(sample.get_id(), sample.get_id().strip())
conditional_block
test_directoryscanner.py
import unittest from os import path from API.directoryscanner import find_runs_in_directory path_to_module = path.abspath(path.dirname(__file__)) class TestDirectoryScanner(unittest.TestCase): def test_sample_names_spaces(self): runs = find_runs_in_directory(path.join(path_to_module, "sample-names-with-spaces"))
self.assertEqual(3, len(samples)) for sample in samples: self.assertEqual(sample.get_id(), sample.get_id().strip()) def test_single_end(self): runs = find_runs_in_directory(path.join(path_to_module, "single_end")) self.assertEqual(1, len(runs)) self.assertEqual("SINGLE_END", runs[0].metadata["layoutType"]) samples = runs[0].sample_list self.assertEqual(3, len(samples)) for sample in samples: self.assertFalse(sample.is_paired_end()) def test_completed_upload(self): runs = find_runs_in_directory(path.join(path_to_module, "completed")) self.assertEqual(0, len(runs)) def test_find_sample_sheet_name_variations(self): runs = find_runs_in_directory(path.join(path_to_module, "sample-sheet-name-variations")) self.assertEqual(1, len(runs))
self.assertEqual(1, len(runs)) samples = runs[0].sample_list
random_line_split
sync.py
import fnmatch import os import re import shutil import sys import uuid from base import Step, StepRunner from tree import Commit here = os.path.abspath(os.path.split(__file__)[0]) bsd_license = """W3C 3-clause BSD License Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of works must retain the original copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the original copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the W3C nor the names of its contributors may be used to endorse or promote products derived from this work without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ def copy_wpt_tree(tree, dest, excludes=None, includes=None): """Copy the working copy of a Tree to a destination directory. :param tree: The Tree to copy. :param dest: The destination directory""" if os.path.exists(dest): assert os.path.isdir(dest) shutil.rmtree(dest) os.mkdir(dest) if excludes is None: excludes = [] excludes = [re.compile(fnmatch.translate(item)) for item in excludes] if includes is None:
includes = [re.compile(fnmatch.translate(item)) for item in includes] for tree_path in tree.paths(): if (any(item.match(tree_path) for item in excludes) and not any(item.match(tree_path) for item in includes)): continue source_path = os.path.join(tree.root, tree_path) dest_path = os.path.join(dest, tree_path) dest_dir = os.path.split(dest_path)[0] if not os.path.isdir(source_path): if not os.path.exists(dest_dir): os.makedirs(dest_dir) shutil.copy2(source_path, dest_path) for source, destination in [("testharness_runner.html", ""), ("testdriver-vendor.js", "resources/")]: source_path = os.path.join(here, os.pardir, source) dest_path = os.path.join(dest, destination, os.path.split(source)[1]) shutil.copy2(source_path, dest_path) add_license(dest) def add_license(dest): """Write the bsd license string to a LICENSE file. :param dest: Directory in which to place the LICENSE file.""" with open(os.path.join(dest, "LICENSE"), "w") as f: f.write(bsd_license) class UpdateCheckout(Step): """Pull changes from upstream into the local sync tree.""" provides = ["local_branch"] def create(self, state): sync_tree = state.sync_tree state.local_branch = uuid.uuid4().hex sync_tree.update(state.sync["remote_url"], state.sync["branch"], state.local_branch) sync_path = os.path.abspath(sync_tree.root) if sync_path not in sys.path: from update import setup_paths setup_paths(sync_path) def restore(self, state): assert os.path.abspath(state.sync_tree.root) in sys.path Step.restore(self, state) class GetSyncTargetCommit(Step): """Find the commit that we will sync to.""" provides = ["sync_commit"] def create(self, state): if state.target_rev is None: #Use upstream branch HEAD as the base commit state.sync_commit = state.sync_tree.get_remote_sha1(state.sync["remote_url"], state.sync["branch"]) else: state.sync_commit = Commit(state.sync_tree, state.rev) state.sync_tree.checkout(state.sync_commit.sha1, state.local_branch, force=True) self.logger.debug("New base commit is %s" % state.sync_commit.sha1) class LoadManifest(Step): """Load the test manifest""" provides = ["manifest_path", "test_manifest"] def create(self, state): from manifest import manifest state.manifest_path = os.path.join(state.metadata_path, "MANIFEST.json") state.test_manifest = manifest.Manifest("/") class UpdateManifest(Step): """Update the manifest to match the tests in the sync tree checkout""" def create(self, state): from manifest import manifest, update update.update(state.sync["path"], state.test_manifest) manifest.write(state.test_manifest, state.manifest_path) class CopyWorkTree(Step): """Copy the sync tree over to the destination in the local tree""" def create(self, state): copy_wpt_tree(state.sync_tree, state.tests_path, excludes=state.path_excludes, includes=state.path_includes) class CreateSyncPatch(Step): """Add the updated test files to a commit/patch in the local tree.""" def create(self, state): if not state.patch: return local_tree = state.local_tree sync_tree = state.sync_tree local_tree.create_patch("web-platform-tests_update_%s" % sync_tree.rev, "Update %s to revision %s" % (state.suite_name, sync_tree.rev)) test_prefix = os.path.relpath(state.tests_path, local_tree.root) local_tree.add_new(test_prefix) local_tree.add_ignored(sync_tree, test_prefix) updated = local_tree.update_patch(include=[state.tests_path, state.metadata_path]) local_tree.commit_patch() if not updated: self.logger.info("Nothing to sync") class SyncFromUpstreamRunner(StepRunner): """(Sub)Runner for doing an upstream sync""" steps = [UpdateCheckout, GetSyncTargetCommit, LoadManifest, UpdateManifest, CopyWorkTree, CreateSyncPatch]
includes = []
conditional_block
sync.py
import fnmatch import os import re import shutil import sys import uuid from base import Step, StepRunner from tree import Commit here = os.path.abspath(os.path.split(__file__)[0]) bsd_license = """W3C 3-clause BSD License Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of works must retain the original copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the original copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the W3C nor the names of its contributors may be used to endorse or promote products derived from this work without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ def copy_wpt_tree(tree, dest, excludes=None, includes=None): """Copy the working copy of a Tree to a destination directory. :param tree: The Tree to copy. :param dest: The destination directory""" if os.path.exists(dest): assert os.path.isdir(dest) shutil.rmtree(dest) os.mkdir(dest) if excludes is None: excludes = [] excludes = [re.compile(fnmatch.translate(item)) for item in excludes] if includes is None: includes = [] includes = [re.compile(fnmatch.translate(item)) for item in includes] for tree_path in tree.paths(): if (any(item.match(tree_path) for item in excludes) and not any(item.match(tree_path) for item in includes)): continue source_path = os.path.join(tree.root, tree_path) dest_path = os.path.join(dest, tree_path) dest_dir = os.path.split(dest_path)[0] if not os.path.isdir(source_path): if not os.path.exists(dest_dir): os.makedirs(dest_dir) shutil.copy2(source_path, dest_path) for source, destination in [("testharness_runner.html", ""), ("testdriver-vendor.js", "resources/")]: source_path = os.path.join(here, os.pardir, source) dest_path = os.path.join(dest, destination, os.path.split(source)[1]) shutil.copy2(source_path, dest_path) add_license(dest) def add_license(dest): """Write the bsd license string to a LICENSE file. :param dest: Directory in which to place the LICENSE file.""" with open(os.path.join(dest, "LICENSE"), "w") as f: f.write(bsd_license) class UpdateCheckout(Step): """Pull changes from upstream into the local sync tree.""" provides = ["local_branch"] def create(self, state): sync_tree = state.sync_tree state.local_branch = uuid.uuid4().hex sync_tree.update(state.sync["remote_url"], state.sync["branch"], state.local_branch) sync_path = os.path.abspath(sync_tree.root) if sync_path not in sys.path: from update import setup_paths setup_paths(sync_path) def restore(self, state): assert os.path.abspath(state.sync_tree.root) in sys.path Step.restore(self, state) class GetSyncTargetCommit(Step): """Find the commit that we will sync to.""" provides = ["sync_commit"] def create(self, state): if state.target_rev is None: #Use upstream branch HEAD as the base commit state.sync_commit = state.sync_tree.get_remote_sha1(state.sync["remote_url"], state.sync["branch"]) else: state.sync_commit = Commit(state.sync_tree, state.rev) state.sync_tree.checkout(state.sync_commit.sha1, state.local_branch, force=True) self.logger.debug("New base commit is %s" % state.sync_commit.sha1) class LoadManifest(Step): """Load the test manifest""" provides = ["manifest_path", "test_manifest"] def
(self, state): from manifest import manifest state.manifest_path = os.path.join(state.metadata_path, "MANIFEST.json") state.test_manifest = manifest.Manifest("/") class UpdateManifest(Step): """Update the manifest to match the tests in the sync tree checkout""" def create(self, state): from manifest import manifest, update update.update(state.sync["path"], state.test_manifest) manifest.write(state.test_manifest, state.manifest_path) class CopyWorkTree(Step): """Copy the sync tree over to the destination in the local tree""" def create(self, state): copy_wpt_tree(state.sync_tree, state.tests_path, excludes=state.path_excludes, includes=state.path_includes) class CreateSyncPatch(Step): """Add the updated test files to a commit/patch in the local tree.""" def create(self, state): if not state.patch: return local_tree = state.local_tree sync_tree = state.sync_tree local_tree.create_patch("web-platform-tests_update_%s" % sync_tree.rev, "Update %s to revision %s" % (state.suite_name, sync_tree.rev)) test_prefix = os.path.relpath(state.tests_path, local_tree.root) local_tree.add_new(test_prefix) local_tree.add_ignored(sync_tree, test_prefix) updated = local_tree.update_patch(include=[state.tests_path, state.metadata_path]) local_tree.commit_patch() if not updated: self.logger.info("Nothing to sync") class SyncFromUpstreamRunner(StepRunner): """(Sub)Runner for doing an upstream sync""" steps = [UpdateCheckout, GetSyncTargetCommit, LoadManifest, UpdateManifest, CopyWorkTree, CreateSyncPatch]
create
identifier_name
sync.py
import fnmatch import os import re import shutil import sys import uuid from base import Step, StepRunner from tree import Commit here = os.path.abspath(os.path.split(__file__)[0]) bsd_license = """W3C 3-clause BSD License Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of works must retain the original copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the original copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the W3C nor the names of its contributors may be used to endorse or promote products derived from this work without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ def copy_wpt_tree(tree, dest, excludes=None, includes=None): """Copy the working copy of a Tree to a destination directory. :param tree: The Tree to copy. :param dest: The destination directory""" if os.path.exists(dest): assert os.path.isdir(dest) shutil.rmtree(dest) os.mkdir(dest) if excludes is None: excludes = [] excludes = [re.compile(fnmatch.translate(item)) for item in excludes] if includes is None: includes = [] includes = [re.compile(fnmatch.translate(item)) for item in includes] for tree_path in tree.paths(): if (any(item.match(tree_path) for item in excludes) and not any(item.match(tree_path) for item in includes)): continue source_path = os.path.join(tree.root, tree_path) dest_path = os.path.join(dest, tree_path) dest_dir = os.path.split(dest_path)[0] if not os.path.isdir(source_path): if not os.path.exists(dest_dir): os.makedirs(dest_dir) shutil.copy2(source_path, dest_path) for source, destination in [("testharness_runner.html", ""), ("testdriver-vendor.js", "resources/")]: source_path = os.path.join(here, os.pardir, source) dest_path = os.path.join(dest, destination, os.path.split(source)[1]) shutil.copy2(source_path, dest_path)
def add_license(dest): """Write the bsd license string to a LICENSE file. :param dest: Directory in which to place the LICENSE file.""" with open(os.path.join(dest, "LICENSE"), "w") as f: f.write(bsd_license) class UpdateCheckout(Step): """Pull changes from upstream into the local sync tree.""" provides = ["local_branch"] def create(self, state): sync_tree = state.sync_tree state.local_branch = uuid.uuid4().hex sync_tree.update(state.sync["remote_url"], state.sync["branch"], state.local_branch) sync_path = os.path.abspath(sync_tree.root) if sync_path not in sys.path: from update import setup_paths setup_paths(sync_path) def restore(self, state): assert os.path.abspath(state.sync_tree.root) in sys.path Step.restore(self, state) class GetSyncTargetCommit(Step): """Find the commit that we will sync to.""" provides = ["sync_commit"] def create(self, state): if state.target_rev is None: #Use upstream branch HEAD as the base commit state.sync_commit = state.sync_tree.get_remote_sha1(state.sync["remote_url"], state.sync["branch"]) else: state.sync_commit = Commit(state.sync_tree, state.rev) state.sync_tree.checkout(state.sync_commit.sha1, state.local_branch, force=True) self.logger.debug("New base commit is %s" % state.sync_commit.sha1) class LoadManifest(Step): """Load the test manifest""" provides = ["manifest_path", "test_manifest"] def create(self, state): from manifest import manifest state.manifest_path = os.path.join(state.metadata_path, "MANIFEST.json") state.test_manifest = manifest.Manifest("/") class UpdateManifest(Step): """Update the manifest to match the tests in the sync tree checkout""" def create(self, state): from manifest import manifest, update update.update(state.sync["path"], state.test_manifest) manifest.write(state.test_manifest, state.manifest_path) class CopyWorkTree(Step): """Copy the sync tree over to the destination in the local tree""" def create(self, state): copy_wpt_tree(state.sync_tree, state.tests_path, excludes=state.path_excludes, includes=state.path_includes) class CreateSyncPatch(Step): """Add the updated test files to a commit/patch in the local tree.""" def create(self, state): if not state.patch: return local_tree = state.local_tree sync_tree = state.sync_tree local_tree.create_patch("web-platform-tests_update_%s" % sync_tree.rev, "Update %s to revision %s" % (state.suite_name, sync_tree.rev)) test_prefix = os.path.relpath(state.tests_path, local_tree.root) local_tree.add_new(test_prefix) local_tree.add_ignored(sync_tree, test_prefix) updated = local_tree.update_patch(include=[state.tests_path, state.metadata_path]) local_tree.commit_patch() if not updated: self.logger.info("Nothing to sync") class SyncFromUpstreamRunner(StepRunner): """(Sub)Runner for doing an upstream sync""" steps = [UpdateCheckout, GetSyncTargetCommit, LoadManifest, UpdateManifest, CopyWorkTree, CreateSyncPatch]
add_license(dest)
random_line_split
sync.py
import fnmatch import os import re import shutil import sys import uuid from base import Step, StepRunner from tree import Commit here = os.path.abspath(os.path.split(__file__)[0]) bsd_license = """W3C 3-clause BSD License Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of works must retain the original copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the original copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the W3C nor the names of its contributors may be used to endorse or promote products derived from this work without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ def copy_wpt_tree(tree, dest, excludes=None, includes=None): """Copy the working copy of a Tree to a destination directory. :param tree: The Tree to copy. :param dest: The destination directory""" if os.path.exists(dest): assert os.path.isdir(dest) shutil.rmtree(dest) os.mkdir(dest) if excludes is None: excludes = [] excludes = [re.compile(fnmatch.translate(item)) for item in excludes] if includes is None: includes = [] includes = [re.compile(fnmatch.translate(item)) for item in includes] for tree_path in tree.paths(): if (any(item.match(tree_path) for item in excludes) and not any(item.match(tree_path) for item in includes)): continue source_path = os.path.join(tree.root, tree_path) dest_path = os.path.join(dest, tree_path) dest_dir = os.path.split(dest_path)[0] if not os.path.isdir(source_path): if not os.path.exists(dest_dir): os.makedirs(dest_dir) shutil.copy2(source_path, dest_path) for source, destination in [("testharness_runner.html", ""), ("testdriver-vendor.js", "resources/")]: source_path = os.path.join(here, os.pardir, source) dest_path = os.path.join(dest, destination, os.path.split(source)[1]) shutil.copy2(source_path, dest_path) add_license(dest) def add_license(dest): """Write the bsd license string to a LICENSE file. :param dest: Directory in which to place the LICENSE file.""" with open(os.path.join(dest, "LICENSE"), "w") as f: f.write(bsd_license) class UpdateCheckout(Step): """Pull changes from upstream into the local sync tree.""" provides = ["local_branch"] def create(self, state): sync_tree = state.sync_tree state.local_branch = uuid.uuid4().hex sync_tree.update(state.sync["remote_url"], state.sync["branch"], state.local_branch) sync_path = os.path.abspath(sync_tree.root) if sync_path not in sys.path: from update import setup_paths setup_paths(sync_path) def restore(self, state): assert os.path.abspath(state.sync_tree.root) in sys.path Step.restore(self, state) class GetSyncTargetCommit(Step): """Find the commit that we will sync to.""" provides = ["sync_commit"] def create(self, state):
class LoadManifest(Step): """Load the test manifest""" provides = ["manifest_path", "test_manifest"] def create(self, state): from manifest import manifest state.manifest_path = os.path.join(state.metadata_path, "MANIFEST.json") state.test_manifest = manifest.Manifest("/") class UpdateManifest(Step): """Update the manifest to match the tests in the sync tree checkout""" def create(self, state): from manifest import manifest, update update.update(state.sync["path"], state.test_manifest) manifest.write(state.test_manifest, state.manifest_path) class CopyWorkTree(Step): """Copy the sync tree over to the destination in the local tree""" def create(self, state): copy_wpt_tree(state.sync_tree, state.tests_path, excludes=state.path_excludes, includes=state.path_includes) class CreateSyncPatch(Step): """Add the updated test files to a commit/patch in the local tree.""" def create(self, state): if not state.patch: return local_tree = state.local_tree sync_tree = state.sync_tree local_tree.create_patch("web-platform-tests_update_%s" % sync_tree.rev, "Update %s to revision %s" % (state.suite_name, sync_tree.rev)) test_prefix = os.path.relpath(state.tests_path, local_tree.root) local_tree.add_new(test_prefix) local_tree.add_ignored(sync_tree, test_prefix) updated = local_tree.update_patch(include=[state.tests_path, state.metadata_path]) local_tree.commit_patch() if not updated: self.logger.info("Nothing to sync") class SyncFromUpstreamRunner(StepRunner): """(Sub)Runner for doing an upstream sync""" steps = [UpdateCheckout, GetSyncTargetCommit, LoadManifest, UpdateManifest, CopyWorkTree, CreateSyncPatch]
if state.target_rev is None: #Use upstream branch HEAD as the base commit state.sync_commit = state.sync_tree.get_remote_sha1(state.sync["remote_url"], state.sync["branch"]) else: state.sync_commit = Commit(state.sync_tree, state.rev) state.sync_tree.checkout(state.sync_commit.sha1, state.local_branch, force=True) self.logger.debug("New base commit is %s" % state.sync_commit.sha1)
identifier_body
test_generated_python.py
import numpy as np import scipy import scipy.linalg import time import os import sys def run_loaded_test(symbolcode, code1, code2, max_seconds=0.1): env = {"np": np, "scipy": scipy, "scipy.linalg": scipy.linalg} exec(symbolcode, env) targets = env['targets'] env1 = env.copy() env2 = env.copy() totaltime = 0.0 time1 = 0.0 time2 = 0.0 n = 0 while totaltime < max_seconds: t1 = time.time() exec(code1, env1) t2 = time.time() exec(code2, env2) t3 = time.time() time1 += t2-t1 time2 += t3-t2 totaltime += t3-t1 n += 1 errs = [np.max(np.abs(np.asarray(env1[target]).flatten()-np.asarray(env2[target]).flatten())) for target in targets] relerrs = [np.max(np.abs(np.log(np.asarray(env1[target]).flatten()/np.asarray(env2[target]).flatten()))) for target in targets] return targets, errs, relerrs, time1/n, time2/n, env1, env2 def run_test(dirname): with open(os.path.join(dirname, "table.py")) as f: symbolcode = f.read() with open(os.path.join(dirname, "naive.py")) as f: naive_code = f.read() with open(os.path.join(dirname, "optimized.py")) as f: optimized_code = f.read() targets, errs, relerrs, naive_time, opt_time, env1, env2 = run_loaded_test(symbolcode, naive_code, optimized_code) print "%s: naive %.0fus optimized %.1fus (%.1f%% speedup)." % (dirname, naive_time*1000000, opt_time*1000000, (1 - opt_time/naive_time)*100.0 ), if (np.max(errs) > 1e-4 and np.max(relerrs) > 1e-4) or np.isnan(np.max(errs)): print " Errors:" for target, err, relerr in zip(targets, errs, relerrs): print " %s: absolute %f relative %f" % (target, err, relerr) t1 = np.asarray(env1[target]) if len(t1.shape) < 2: t1 = t1.reshape((1, -1)) t2 = np.asarray(env2[target]) if len(t2.shape) < 2: t2 = t2.reshape((1, -1)) np.savetxt(os.path.join(dirname, '%s_naive.txt' % target), t1) np.savetxt(os.path.join(dirname, '%s_optimized.txt' % target), t2) print " ... output saved to", dirname else: print def run_tests(dirname): for testdir in os.listdir(dirname):
if __name__ == "__main__": default_test_dir = "tests/gen_python/" run_tests(default_test_dir)
run_test(os.path.join(dirname, testdir))
conditional_block
test_generated_python.py
import numpy as np import scipy import scipy.linalg import time import os import sys def run_loaded_test(symbolcode, code1, code2, max_seconds=0.1):
def run_test(dirname): with open(os.path.join(dirname, "table.py")) as f: symbolcode = f.read() with open(os.path.join(dirname, "naive.py")) as f: naive_code = f.read() with open(os.path.join(dirname, "optimized.py")) as f: optimized_code = f.read() targets, errs, relerrs, naive_time, opt_time, env1, env2 = run_loaded_test(symbolcode, naive_code, optimized_code) print "%s: naive %.0fus optimized %.1fus (%.1f%% speedup)." % (dirname, naive_time*1000000, opt_time*1000000, (1 - opt_time/naive_time)*100.0 ), if (np.max(errs) > 1e-4 and np.max(relerrs) > 1e-4) or np.isnan(np.max(errs)): print " Errors:" for target, err, relerr in zip(targets, errs, relerrs): print " %s: absolute %f relative %f" % (target, err, relerr) t1 = np.asarray(env1[target]) if len(t1.shape) < 2: t1 = t1.reshape((1, -1)) t2 = np.asarray(env2[target]) if len(t2.shape) < 2: t2 = t2.reshape((1, -1)) np.savetxt(os.path.join(dirname, '%s_naive.txt' % target), t1) np.savetxt(os.path.join(dirname, '%s_optimized.txt' % target), t2) print " ... output saved to", dirname else: print def run_tests(dirname): for testdir in os.listdir(dirname): run_test(os.path.join(dirname, testdir)) if __name__ == "__main__": default_test_dir = "tests/gen_python/" run_tests(default_test_dir)
env = {"np": np, "scipy": scipy, "scipy.linalg": scipy.linalg} exec(symbolcode, env) targets = env['targets'] env1 = env.copy() env2 = env.copy() totaltime = 0.0 time1 = 0.0 time2 = 0.0 n = 0 while totaltime < max_seconds: t1 = time.time() exec(code1, env1) t2 = time.time() exec(code2, env2) t3 = time.time() time1 += t2-t1 time2 += t3-t2 totaltime += t3-t1 n += 1 errs = [np.max(np.abs(np.asarray(env1[target]).flatten()-np.asarray(env2[target]).flatten())) for target in targets] relerrs = [np.max(np.abs(np.log(np.asarray(env1[target]).flatten()/np.asarray(env2[target]).flatten()))) for target in targets] return targets, errs, relerrs, time1/n, time2/n, env1, env2
identifier_body
test_generated_python.py
import numpy as np import scipy import scipy.linalg import time import os import sys def run_loaded_test(symbolcode, code1, code2, max_seconds=0.1): env = {"np": np, "scipy": scipy, "scipy.linalg": scipy.linalg} exec(symbolcode, env) targets = env['targets'] env1 = env.copy() env2 = env.copy() totaltime = 0.0 time1 = 0.0 time2 = 0.0 n = 0 while totaltime < max_seconds: t1 = time.time() exec(code1, env1) t2 = time.time() exec(code2, env2) t3 = time.time() time1 += t2-t1 time2 += t3-t2 totaltime += t3-t1 n += 1 errs = [np.max(np.abs(np.asarray(env1[target]).flatten()-np.asarray(env2[target]).flatten())) for target in targets] relerrs = [np.max(np.abs(np.log(np.asarray(env1[target]).flatten()/np.asarray(env2[target]).flatten()))) for target in targets] return targets, errs, relerrs, time1/n, time2/n, env1, env2 def
(dirname): with open(os.path.join(dirname, "table.py")) as f: symbolcode = f.read() with open(os.path.join(dirname, "naive.py")) as f: naive_code = f.read() with open(os.path.join(dirname, "optimized.py")) as f: optimized_code = f.read() targets, errs, relerrs, naive_time, opt_time, env1, env2 = run_loaded_test(symbolcode, naive_code, optimized_code) print "%s: naive %.0fus optimized %.1fus (%.1f%% speedup)." % (dirname, naive_time*1000000, opt_time*1000000, (1 - opt_time/naive_time)*100.0 ), if (np.max(errs) > 1e-4 and np.max(relerrs) > 1e-4) or np.isnan(np.max(errs)): print " Errors:" for target, err, relerr in zip(targets, errs, relerrs): print " %s: absolute %f relative %f" % (target, err, relerr) t1 = np.asarray(env1[target]) if len(t1.shape) < 2: t1 = t1.reshape((1, -1)) t2 = np.asarray(env2[target]) if len(t2.shape) < 2: t2 = t2.reshape((1, -1)) np.savetxt(os.path.join(dirname, '%s_naive.txt' % target), t1) np.savetxt(os.path.join(dirname, '%s_optimized.txt' % target), t2) print " ... output saved to", dirname else: print def run_tests(dirname): for testdir in os.listdir(dirname): run_test(os.path.join(dirname, testdir)) if __name__ == "__main__": default_test_dir = "tests/gen_python/" run_tests(default_test_dir)
run_test
identifier_name
test_generated_python.py
import numpy as np import scipy import scipy.linalg import time import os import sys def run_loaded_test(symbolcode, code1, code2, max_seconds=0.1): env = {"np": np, "scipy": scipy, "scipy.linalg": scipy.linalg} exec(symbolcode, env) targets = env['targets'] env1 = env.copy() env2 = env.copy() totaltime = 0.0 time1 = 0.0 time2 = 0.0
t2 = time.time() exec(code2, env2) t3 = time.time() time1 += t2-t1 time2 += t3-t2 totaltime += t3-t1 n += 1 errs = [np.max(np.abs(np.asarray(env1[target]).flatten()-np.asarray(env2[target]).flatten())) for target in targets] relerrs = [np.max(np.abs(np.log(np.asarray(env1[target]).flatten()/np.asarray(env2[target]).flatten()))) for target in targets] return targets, errs, relerrs, time1/n, time2/n, env1, env2 def run_test(dirname): with open(os.path.join(dirname, "table.py")) as f: symbolcode = f.read() with open(os.path.join(dirname, "naive.py")) as f: naive_code = f.read() with open(os.path.join(dirname, "optimized.py")) as f: optimized_code = f.read() targets, errs, relerrs, naive_time, opt_time, env1, env2 = run_loaded_test(symbolcode, naive_code, optimized_code) print "%s: naive %.0fus optimized %.1fus (%.1f%% speedup)." % (dirname, naive_time*1000000, opt_time*1000000, (1 - opt_time/naive_time)*100.0 ), if (np.max(errs) > 1e-4 and np.max(relerrs) > 1e-4) or np.isnan(np.max(errs)): print " Errors:" for target, err, relerr in zip(targets, errs, relerrs): print " %s: absolute %f relative %f" % (target, err, relerr) t1 = np.asarray(env1[target]) if len(t1.shape) < 2: t1 = t1.reshape((1, -1)) t2 = np.asarray(env2[target]) if len(t2.shape) < 2: t2 = t2.reshape((1, -1)) np.savetxt(os.path.join(dirname, '%s_naive.txt' % target), t1) np.savetxt(os.path.join(dirname, '%s_optimized.txt' % target), t2) print " ... output saved to", dirname else: print def run_tests(dirname): for testdir in os.listdir(dirname): run_test(os.path.join(dirname, testdir)) if __name__ == "__main__": default_test_dir = "tests/gen_python/" run_tests(default_test_dir)
n = 0 while totaltime < max_seconds: t1 = time.time() exec(code1, env1)
random_line_split
migrate.py
from optparse import OptionParser import simplejson as json import spotify_client import datatype import datetime import time import calendar import wiki import omni_redis def migrate_v1(path_in, path_out): client = spotify_client.Client() uris = [] with open(path_in, 'rb') as f: for line in f: doc = json.loads(line) uris.append(doc['u']) tracks = client.track_data(uris) with open(path_out, 'wb') as f: for t in tracks: ts = calendar.timegm(datetime.datetime.now().utctimetuple()) t.meta = datatype.Meta(date_added=ts, last_modified=ts) f.write('%s\n' % json.dumps(t._to_dict())) def migrate_v2(path_in, view): with open(path_in, 'rb') as f: tracks = [datatype.track_from_dict(json.loads(line)) for line in f] for t in tracks: t.meta.date_added = t.meta.date_added or int(round(time.time())) t.meta.last_modified = t.meta.last_modified or int(round(time.time())) print 'putting %d tracks' % len(tracks) omni_redis.put_view('default', view, tracks) migrate = migrate_v2 def add_countries(path_in, path_out):
def main(): parser = OptionParser() parser.add_option('-i', dest='input') parser.add_option('-o', dest='output') parser.add_option('-w', dest='wiki', action="store_true") options, args = parser.parse_args() if options.wiki: add_countries(options.input, options.output) else: migrate(options.input, options.output) if __name__ == '__main__': main()
tracks = [] artist_countries = {} with open(path_in, 'rb') as f: for line in f: doc = json.loads(line) tracks.append(doc) artist_countries[doc['a']['n']] = None for i,artist in enumerate(artist_countries.iterkeys()): artist_countries[artist]=wiki.country_for_artist(artist) print '%d/%d %s: %s' % (i+1, len(artist_countries), artist, artist_countries[artist]) with open(path_out, 'wb') as f: for t in tracks: t['a']['c'] = artist_countries[t['a']['n']] f.write('%s\n' % json.dumps(t))
identifier_body
migrate.py
from optparse import OptionParser import simplejson as json import spotify_client import datatype import datetime import time import calendar import wiki import omni_redis def migrate_v1(path_in, path_out): client = spotify_client.Client() uris = [] with open(path_in, 'rb') as f: for line in f: doc = json.loads(line) uris.append(doc['u']) tracks = client.track_data(uris) with open(path_out, 'wb') as f: for t in tracks: ts = calendar.timegm(datetime.datetime.now().utctimetuple()) t.meta = datatype.Meta(date_added=ts, last_modified=ts) f.write('%s\n' % json.dumps(t._to_dict())) def migrate_v2(path_in, view): with open(path_in, 'rb') as f: tracks = [datatype.track_from_dict(json.loads(line)) for line in f] for t in tracks: t.meta.date_added = t.meta.date_added or int(round(time.time())) t.meta.last_modified = t.meta.last_modified or int(round(time.time())) print 'putting %d tracks' % len(tracks) omni_redis.put_view('default', view, tracks) migrate = migrate_v2 def add_countries(path_in, path_out): tracks = [] artist_countries = {} with open(path_in, 'rb') as f: for line in f: doc = json.loads(line) tracks.append(doc) artist_countries[doc['a']['n']] = None for i,artist in enumerate(artist_countries.iterkeys()): artist_countries[artist]=wiki.country_for_artist(artist) print '%d/%d %s: %s' % (i+1, len(artist_countries), artist, artist_countries[artist]) with open(path_out, 'wb') as f: for t in tracks: t['a']['c'] = artist_countries[t['a']['n']] f.write('%s\n' % json.dumps(t)) def
(): parser = OptionParser() parser.add_option('-i', dest='input') parser.add_option('-o', dest='output') parser.add_option('-w', dest='wiki', action="store_true") options, args = parser.parse_args() if options.wiki: add_countries(options.input, options.output) else: migrate(options.input, options.output) if __name__ == '__main__': main()
main
identifier_name
migrate.py
from optparse import OptionParser import simplejson as json import spotify_client import datatype import datetime import time import calendar import wiki import omni_redis def migrate_v1(path_in, path_out): client = spotify_client.Client() uris = [] with open(path_in, 'rb') as f: for line in f: doc = json.loads(line) uris.append(doc['u']) tracks = client.track_data(uris) with open(path_out, 'wb') as f: for t in tracks: ts = calendar.timegm(datetime.datetime.now().utctimetuple()) t.meta = datatype.Meta(date_added=ts, last_modified=ts) f.write('%s\n' % json.dumps(t._to_dict())) def migrate_v2(path_in, view): with open(path_in, 'rb') as f: tracks = [datatype.track_from_dict(json.loads(line)) for line in f] for t in tracks:
print 'putting %d tracks' % len(tracks) omni_redis.put_view('default', view, tracks) migrate = migrate_v2 def add_countries(path_in, path_out): tracks = [] artist_countries = {} with open(path_in, 'rb') as f: for line in f: doc = json.loads(line) tracks.append(doc) artist_countries[doc['a']['n']] = None for i,artist in enumerate(artist_countries.iterkeys()): artist_countries[artist]=wiki.country_for_artist(artist) print '%d/%d %s: %s' % (i+1, len(artist_countries), artist, artist_countries[artist]) with open(path_out, 'wb') as f: for t in tracks: t['a']['c'] = artist_countries[t['a']['n']] f.write('%s\n' % json.dumps(t)) def main(): parser = OptionParser() parser.add_option('-i', dest='input') parser.add_option('-o', dest='output') parser.add_option('-w', dest='wiki', action="store_true") options, args = parser.parse_args() if options.wiki: add_countries(options.input, options.output) else: migrate(options.input, options.output) if __name__ == '__main__': main()
t.meta.date_added = t.meta.date_added or int(round(time.time())) t.meta.last_modified = t.meta.last_modified or int(round(time.time()))
conditional_block
migrate.py
from optparse import OptionParser import simplejson as json import spotify_client import datatype import datetime import time import calendar import wiki import omni_redis def migrate_v1(path_in, path_out): client = spotify_client.Client() uris = [] with open(path_in, 'rb') as f: for line in f: doc = json.loads(line) uris.append(doc['u']) tracks = client.track_data(uris) with open(path_out, 'wb') as f: for t in tracks: ts = calendar.timegm(datetime.datetime.now().utctimetuple()) t.meta = datatype.Meta(date_added=ts, last_modified=ts) f.write('%s\n' % json.dumps(t._to_dict())) def migrate_v2(path_in, view): with open(path_in, 'rb') as f: tracks = [datatype.track_from_dict(json.loads(line)) for line in f] for t in tracks: t.meta.date_added = t.meta.date_added or int(round(time.time())) t.meta.last_modified = t.meta.last_modified or int(round(time.time())) print 'putting %d tracks' % len(tracks) omni_redis.put_view('default', view, tracks) migrate = migrate_v2 def add_countries(path_in, path_out): tracks = [] artist_countries = {} with open(path_in, 'rb') as f: for line in f: doc = json.loads(line) tracks.append(doc) artist_countries[doc['a']['n']] = None for i,artist in enumerate(artist_countries.iterkeys()): artist_countries[artist]=wiki.country_for_artist(artist) print '%d/%d %s: %s' % (i+1, len(artist_countries), artist, artist_countries[artist]) with open(path_out, 'wb') as f: for t in tracks: t['a']['c'] = artist_countries[t['a']['n']]
f.write('%s\n' % json.dumps(t)) def main(): parser = OptionParser() parser.add_option('-i', dest='input') parser.add_option('-o', dest='output') parser.add_option('-w', dest='wiki', action="store_true") options, args = parser.parse_args() if options.wiki: add_countries(options.input, options.output) else: migrate(options.input, options.output) if __name__ == '__main__': main()
random_line_split
training_utils_test.ts
/** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import '@tensorflow/tfjs-node'; import * as tf from '@tensorflow/tfjs-core'; // tslint:disable-next-line: no-imports-from-dist import {describeWithFlags, NODE_ENVS} from '@tensorflow/tfjs-core/dist/jasmine_util'; import {expectTensorsClose} from './test_utils'; import {balancedTrainValSplit} from './training_utils'; describeWithFlags('balancedTrainValSplit', NODE_ENVS, () => { it('Enough data for split', () => { const xs = tf.randomNormal([8, 3]); const ys = tf.oneHot(tf.tensor1d([0, 0, 0, 0, 1, 1, 1, 1], 'int32'), 2); const {trainXs, trainYs, valXs, valYs} = balancedTrainValSplit(xs, ys, 0.25); expect(trainXs.shape).toEqual([6, 3]); expect(trainYs.shape).toEqual([6, 2]); expect(valXs.shape).toEqual([2, 3]); expect(valYs.shape).toEqual([2, 2]); expectTensorsClose(tf.sum(trainYs, 0), tf.tensor1d([3, 3], 'int32')); expectTensorsClose(tf.sum(valYs, 0), tf.tensor1d([1, 1], 'int32')); }); it('Not enough data for split', () => { const xs = tf.randomNormal([8, 3]); const ys = tf.oneHot(tf.tensor1d([0, 0, 0, 0, 1, 1, 1, 1], 'int32'), 2); const {trainXs, trainYs, valXs, valYs} = balancedTrainValSplit(xs, ys, 0.01); expect(trainXs.shape).toEqual([8, 3]); expect(trainYs.shape).toEqual([8, 2]); expect(valXs.shape).toEqual([0, 3]); expect(valYs.shape).toEqual([0, 2]); }); it('Invalid valSplit leads to Error', () => { const xs = tf.randomNormal([8, 3]); const ys = tf.oneHot(tf.tensor1d([0, 0, 0, 0, 1, 1, 1, 1], 'int32'), 2); expect(() => balancedTrainValSplit(xs, ys, -0.2)).toThrow(); expect(() => balancedTrainValSplit(xs, ys, 0)).toThrow(); expect(() => balancedTrainValSplit(xs, ys, 1)).toThrow(); expect(() => balancedTrainValSplit(xs, ys, 1.2)).toThrow(); }); });
random_line_split
expr.rs
#![allow(dead_code)] use super::*; use std::fmt; use std::sync::Arc; #[derive(Clone, Debug)] pub enum Expr { Nil, Bool(bool), Int(i64), Flt(f64), Str(String), Sym(Symbol), Func(Arc<Function>), Macro(Arc<Macro>), List(List), Vector(Vector), Map(Map), } impl Expr {
} else { None } } pub fn int(&self) -> Option<i64> { if let Expr::Int(x) = *self { Some(x) } else { None } } pub fn flt(&self) -> Option<f64> { if let Expr::Flt(x) = *self { Some(x) } else { None } } pub fn str(&self) -> Option<&str> { if let Expr::Str(ref x) = *self { Some(x) } else { None } } pub fn sym(&self) -> Option<&Symbol> { if let Expr::Sym(ref x) = *self { Some(x) } else { None } } pub fn list(&self) -> Option<&List> { if let Expr::List(ref x) = *self { Some(x) } else { None } } pub fn vector(&self) -> Option<&Vector> { if let Expr::Vector(ref x) = *self { Some(x) } else { None } } pub fn func(&self) -> Option<Arc<Function>> { if let Expr::Func(ref x) = *self { Some(x.clone()) } else { None } } pub fn truthiness(&self) -> bool { match *self { Expr::Nil => false, Expr::Bool(b) => b, _ => true, } } pub fn is_int(&self) -> bool { self.int().is_some() } pub fn is_flt(&self) -> bool { self.flt().is_some() } pub fn is_num(&self) -> bool { match *self { Expr::Flt(_) | Expr::Int(_) => true, _ => false, } } pub fn map_int<E, F>(self, f: F) -> Expr where F: FnOnce(i64) -> E, E: Into<Expr> { match self { Expr::Int(int) => f(int).into(), _ => self, } } pub fn map_flt<E, F>(self, f: F) -> Expr where F: FnOnce(f64) -> E, E: Into<Expr> { match self { Expr::Flt(flt) => f(flt).into(), _ => self, } } } impl fmt::Display for Expr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Expr::Nil => write!(f, "()"), Expr::Bool(boolean) => write!(f, "#{}", if boolean { "t" } else { "f" }), Expr::Int(int) => write!(f, "{}", int), Expr::Flt(flt) => write!(f, "{}", flt), Expr::Str(ref string) => write!(f, "\"{}\"", string), Expr::Sym(ref sym) => write!(f, "{}", sym.0), Expr::Func(ref func) => write!(f, "{}", func), Expr::Macro(ref mac) => write!(f, "{}", mac), Expr::List(ref list) => write!(f, "{}", list), Expr::Vector(ref vec) => write!(f, "{}", vec), Expr::Map(ref map) => write!(f, "{}", map), } } } impl PartialEq for Expr { fn eq(&self, other: &Self) -> bool { use self::Expr::*; match (self, other) { (&Nil, &Nil) => true, (&Bool(ref a), &Bool(ref b)) => a == b, (&Int(ref a), &Int(ref b)) => a == b, (&Flt(ref a), &Flt(ref b)) => a == b, (&Str(ref a), &Str(ref b)) => a == b, (&Sym(ref a), &Sym(ref b)) => a == b, (&Func(_), &Func(_)) => false, (&Macro(_), &Macro(_)) => false, (&List(ref a), &List(ref b)) => a == b, (&Vector(ref a), &Vector(ref b)) => a == b, (&Map(ref a), &Map(ref b)) => a == b, _ => false, } } } #[cfg(test)] mod test { use super::*; use env::Env; use ops; #[test] fn call_fn() { let env = ops::env(); let add = env.lookup("+").clone().and_then(|f| f.func()).expect( "Expected #[+] in builtins", ); let nums: Vec<Expr> = vec![1i64, 2i64].into_iter().map(Expr::from).collect(); let result = add.apply(nums.as_slice(), env.clone()); assert_eq!(Expr::from(3), result.unwrap()); } #[test] fn test_env() { let new_scope = Env::default(); assert!(new_scope.lookup("hello").is_none()); } }
pub fn boolean(&self) -> Option<bool> { if let Expr::Bool(x) = *self { Some(x)
random_line_split
expr.rs
#![allow(dead_code)] use super::*; use std::fmt; use std::sync::Arc; #[derive(Clone, Debug)] pub enum Expr { Nil, Bool(bool), Int(i64), Flt(f64), Str(String), Sym(Symbol), Func(Arc<Function>), Macro(Arc<Macro>), List(List), Vector(Vector), Map(Map), } impl Expr { pub fn boolean(&self) -> Option<bool> { if let Expr::Bool(x) = *self { Some(x) } else { None } } pub fn int(&self) -> Option<i64> { if let Expr::Int(x) = *self { Some(x) } else { None } } pub fn flt(&self) -> Option<f64> { if let Expr::Flt(x) = *self { Some(x) } else { None } } pub fn str(&self) -> Option<&str> { if let Expr::Str(ref x) = *self { Some(x) } else { None } } pub fn sym(&self) -> Option<&Symbol> { if let Expr::Sym(ref x) = *self { Some(x) } else { None } } pub fn list(&self) -> Option<&List> { if let Expr::List(ref x) = *self { Some(x) } else { None } } pub fn vector(&self) -> Option<&Vector> { if let Expr::Vector(ref x) = *self { Some(x) } else { None } } pub fn func(&self) -> Option<Arc<Function>> { if let Expr::Func(ref x) = *self { Some(x.clone()) } else { None } } pub fn truthiness(&self) -> bool { match *self { Expr::Nil => false, Expr::Bool(b) => b, _ => true, } } pub fn is_int(&self) -> bool
pub fn is_flt(&self) -> bool { self.flt().is_some() } pub fn is_num(&self) -> bool { match *self { Expr::Flt(_) | Expr::Int(_) => true, _ => false, } } pub fn map_int<E, F>(self, f: F) -> Expr where F: FnOnce(i64) -> E, E: Into<Expr> { match self { Expr::Int(int) => f(int).into(), _ => self, } } pub fn map_flt<E, F>(self, f: F) -> Expr where F: FnOnce(f64) -> E, E: Into<Expr> { match self { Expr::Flt(flt) => f(flt).into(), _ => self, } } } impl fmt::Display for Expr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Expr::Nil => write!(f, "()"), Expr::Bool(boolean) => write!(f, "#{}", if boolean { "t" } else { "f" }), Expr::Int(int) => write!(f, "{}", int), Expr::Flt(flt) => write!(f, "{}", flt), Expr::Str(ref string) => write!(f, "\"{}\"", string), Expr::Sym(ref sym) => write!(f, "{}", sym.0), Expr::Func(ref func) => write!(f, "{}", func), Expr::Macro(ref mac) => write!(f, "{}", mac), Expr::List(ref list) => write!(f, "{}", list), Expr::Vector(ref vec) => write!(f, "{}", vec), Expr::Map(ref map) => write!(f, "{}", map), } } } impl PartialEq for Expr { fn eq(&self, other: &Self) -> bool { use self::Expr::*; match (self, other) { (&Nil, &Nil) => true, (&Bool(ref a), &Bool(ref b)) => a == b, (&Int(ref a), &Int(ref b)) => a == b, (&Flt(ref a), &Flt(ref b)) => a == b, (&Str(ref a), &Str(ref b)) => a == b, (&Sym(ref a), &Sym(ref b)) => a == b, (&Func(_), &Func(_)) => false, (&Macro(_), &Macro(_)) => false, (&List(ref a), &List(ref b)) => a == b, (&Vector(ref a), &Vector(ref b)) => a == b, (&Map(ref a), &Map(ref b)) => a == b, _ => false, } } } #[cfg(test)] mod test { use super::*; use env::Env; use ops; #[test] fn call_fn() { let env = ops::env(); let add = env.lookup("+").clone().and_then(|f| f.func()).expect( "Expected #[+] in builtins", ); let nums: Vec<Expr> = vec![1i64, 2i64].into_iter().map(Expr::from).collect(); let result = add.apply(nums.as_slice(), env.clone()); assert_eq!(Expr::from(3), result.unwrap()); } #[test] fn test_env() { let new_scope = Env::default(); assert!(new_scope.lookup("hello").is_none()); } }
{ self.int().is_some() }
identifier_body
expr.rs
#![allow(dead_code)] use super::*; use std::fmt; use std::sync::Arc; #[derive(Clone, Debug)] pub enum Expr { Nil, Bool(bool), Int(i64), Flt(f64), Str(String), Sym(Symbol), Func(Arc<Function>), Macro(Arc<Macro>), List(List), Vector(Vector), Map(Map), } impl Expr { pub fn boolean(&self) -> Option<bool> { if let Expr::Bool(x) = *self { Some(x) } else { None } } pub fn int(&self) -> Option<i64> { if let Expr::Int(x) = *self { Some(x) } else { None } } pub fn flt(&self) -> Option<f64> { if let Expr::Flt(x) = *self { Some(x) } else { None } } pub fn str(&self) -> Option<&str> { if let Expr::Str(ref x) = *self { Some(x) } else { None } } pub fn sym(&self) -> Option<&Symbol> { if let Expr::Sym(ref x) = *self { Some(x) } else { None } } pub fn list(&self) -> Option<&List> { if let Expr::List(ref x) = *self { Some(x) } else { None } } pub fn
(&self) -> Option<&Vector> { if let Expr::Vector(ref x) = *self { Some(x) } else { None } } pub fn func(&self) -> Option<Arc<Function>> { if let Expr::Func(ref x) = *self { Some(x.clone()) } else { None } } pub fn truthiness(&self) -> bool { match *self { Expr::Nil => false, Expr::Bool(b) => b, _ => true, } } pub fn is_int(&self) -> bool { self.int().is_some() } pub fn is_flt(&self) -> bool { self.flt().is_some() } pub fn is_num(&self) -> bool { match *self { Expr::Flt(_) | Expr::Int(_) => true, _ => false, } } pub fn map_int<E, F>(self, f: F) -> Expr where F: FnOnce(i64) -> E, E: Into<Expr> { match self { Expr::Int(int) => f(int).into(), _ => self, } } pub fn map_flt<E, F>(self, f: F) -> Expr where F: FnOnce(f64) -> E, E: Into<Expr> { match self { Expr::Flt(flt) => f(flt).into(), _ => self, } } } impl fmt::Display for Expr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Expr::Nil => write!(f, "()"), Expr::Bool(boolean) => write!(f, "#{}", if boolean { "t" } else { "f" }), Expr::Int(int) => write!(f, "{}", int), Expr::Flt(flt) => write!(f, "{}", flt), Expr::Str(ref string) => write!(f, "\"{}\"", string), Expr::Sym(ref sym) => write!(f, "{}", sym.0), Expr::Func(ref func) => write!(f, "{}", func), Expr::Macro(ref mac) => write!(f, "{}", mac), Expr::List(ref list) => write!(f, "{}", list), Expr::Vector(ref vec) => write!(f, "{}", vec), Expr::Map(ref map) => write!(f, "{}", map), } } } impl PartialEq for Expr { fn eq(&self, other: &Self) -> bool { use self::Expr::*; match (self, other) { (&Nil, &Nil) => true, (&Bool(ref a), &Bool(ref b)) => a == b, (&Int(ref a), &Int(ref b)) => a == b, (&Flt(ref a), &Flt(ref b)) => a == b, (&Str(ref a), &Str(ref b)) => a == b, (&Sym(ref a), &Sym(ref b)) => a == b, (&Func(_), &Func(_)) => false, (&Macro(_), &Macro(_)) => false, (&List(ref a), &List(ref b)) => a == b, (&Vector(ref a), &Vector(ref b)) => a == b, (&Map(ref a), &Map(ref b)) => a == b, _ => false, } } } #[cfg(test)] mod test { use super::*; use env::Env; use ops; #[test] fn call_fn() { let env = ops::env(); let add = env.lookup("+").clone().and_then(|f| f.func()).expect( "Expected #[+] in builtins", ); let nums: Vec<Expr> = vec![1i64, 2i64].into_iter().map(Expr::from).collect(); let result = add.apply(nums.as_slice(), env.clone()); assert_eq!(Expr::from(3), result.unwrap()); } #[test] fn test_env() { let new_scope = Env::default(); assert!(new_scope.lookup("hello").is_none()); } }
vector
identifier_name
astconv.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * Conversion from AST representation of types to the ty.rs * representation. The main routine here is `ast_ty_to_ty()`: each use * is parameterized by an instance of `AstConv` and a `region_scope`. * * The parameterization of `ast_ty_to_ty()` is because it behaves * somewhat differently during the collect and check phases, particularly * with respect to looking up the types of top-level items. In the * collect phase, the crate context is used as the `AstConv` instance; * in this phase, the `get_item_ty()` function triggers a recursive call * to `ty_of_item()` (note that `ast_ty_to_ty()` will detect recursive * types and report an error). In the check phase, when the @FnCtxt is * used as the `AstConv`, `get_item_ty()` just looks up the item type in * `tcx.tcache`. * * The `region_scope` trait controls how region references are * handled. It has two methods which are used to resolve anonymous * region references (e.g., `&T`) and named region references (e.g., * `&a.T`). There are numerous region scopes that can be used, but most * commonly you want either `empty_rscope`, which permits only the static * region, or `type_rscope`, which permits the self region if the type in * question is parameterized by a region. * * Unlike the `AstConv` trait, the region scope can change as we descend * the type. This is to accommodate the fact that (a) fn types are binding * scopes and (b) the default region may change. To understand case (a), * consider something like: * * type foo = { x: &a.int, y: &fn(&a.int) } * * The type of `x` is an error because there is no region `a` in scope. * In the type of `y`, however, region `a` is considered a bound region * as it does not already appear in scope. * * Case (b) says that if you have a type: * type foo<'self> = ...; * type bar = fn(&foo, &a.foo) * The fully expanded version of type bar is: * type bar = fn(&'foo &, &a.foo<'a>) * Note that the self region for the `foo` defaulted to `&` in the first * case but `&a` in the second. Basically, defaults that appear inside * an rptr (`&r.T`) use the region `r` that appears in the rptr. */ use core::prelude::*; use middle::const_eval; use middle::ty::{arg, substs}; use middle::ty::{ty_param_substs_and_ty}; use middle::ty; use middle::typeck::rscope::in_binding_rscope; use middle::typeck::rscope::{region_scope, RegionError}; use middle::typeck::rscope::RegionParamNames; use core::result; use core::vec; use syntax::abi::AbiSet; use syntax::{ast, ast_util}; use syntax::codemap::span; use syntax::opt_vec::OptVec; use syntax::opt_vec; use syntax::print::pprust::{lifetime_to_str, path_to_str}; use syntax::parse::token::special_idents; use util::common::indenter; pub trait AstConv { fn tcx(&self) -> ty::ctxt; fn get_item_ty(&self, id: ast::def_id) -> ty::ty_param_bounds_and_ty; // what type should we use when a type is omitted? fn ty_infer(&self, span: span) -> ty::t; } pub fn get_region_reporting_err( tcx: ty::ctxt, span: span, a_r: Option<@ast::Lifetime>, res: Result<ty::Region, RegionError>) -> ty::Region { match res { result::Ok(r) => r, result::Err(ref e) => { let descr = match a_r { None => ~"anonymous lifetime", Some(a) => fmt!("lifetime %s", lifetime_to_str(a, tcx.sess.intr())) }; tcx.sess.span_err( span, fmt!("Illegal %s: %s", descr, e.msg)); e.replacement } } } pub fn ast_region_to_region<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, default_span: span, opt_lifetime: Option<@ast::Lifetime>) -> ty::Region { let (span, res) = match opt_lifetime { None => { (default_span, rscope.anon_region(default_span)) } Some(ref lifetime) if lifetime.ident == special_idents::static => { (lifetime.span, Ok(ty::re_static)) } Some(ref lifetime) if lifetime.ident == special_idents::self_ => { (lifetime.span, rscope.self_region(lifetime.span)) } Some(ref lifetime) => { (lifetime.span, rscope.named_region(lifetime.span, lifetime.ident)) } }; get_region_reporting_err(self.tcx(), span, opt_lifetime, res) } pub fn ast_path_to_substs_and_ty<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, did: ast::def_id, path: @ast::path) -> ty_param_substs_and_ty { let tcx = self.tcx(); let ty::ty_param_bounds_and_ty { bounds: decl_bounds, region_param: decl_rp, ty: decl_ty } = self.get_item_ty(did); debug!("ast_path_to_substs_and_ty: did=%? decl_rp=%?", did, decl_rp); // If the type is parameterized by the self region, then replace self // region with the current anon region binding (in other words, // whatever & would get replaced with). let self_r = match (decl_rp, path.rp) { (None, None) => { None } (None, Some(_)) => { tcx.sess.span_err( path.span, fmt!("no region bound is allowed on `%s`, \ which is not declared as containing region pointers", ty::item_path_str(tcx, did))); None } (Some(_), None) => { let res = rscope.anon_region(path.span); let r = get_region_reporting_err(self.tcx(), path.span, None, res); Some(r) } (Some(_), Some(_)) => { Some(ast_region_to_region(self, rscope, path.span, path.rp)) } }; // Convert the type parameters supplied by the user. if !vec::same_length(*decl_bounds, path.types) { self.tcx().sess.span_fatal( path.span, fmt!("wrong number of type arguments: expected %u but found %u", (*decl_bounds).len(), path.types.len())); } let tps = path.types.map(|a_t| ast_ty_to_ty(self, rscope, *a_t)); let substs = substs {self_r:self_r, self_ty:None, tps:tps}; let ty = ty::subst(tcx, &substs, decl_ty); ty_param_substs_and_ty { substs: substs, ty: ty } } pub fn ast_path_to_ty<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, did: ast::def_id, path: @ast::path) -> ty_param_substs_and_ty
pub static NO_REGIONS: uint = 1; pub static NO_TPS: uint = 2; // Parses the programmer's textual representation of a type into our // internal notion of a type. `getter` is a function that returns the type // corresponding to a definition ID: pub fn ast_ty_to_ty<AC:AstConv, RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, &&ast_ty: @ast::Ty) -> ty::t { fn ast_mt_to_mt<AC:AstConv, RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, mt: &ast::mt) -> ty::mt { ty::mt {ty: ast_ty_to_ty(self, rscope, mt.ty), mutbl: mt.mutbl} } // Handle @, ~, and & being able to mean estrs and evecs. // If a_seq_ty is a str or a vec, make it an estr/evec. // Also handle first-class trait types. fn mk_pointer<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, a_seq_ty: &ast::mt, vst: ty::vstore, constr: &fn(ty::mt) -> ty::t) -> ty::t { let tcx = self.tcx(); match a_seq_ty.ty.node { ast::ty_vec(ref mt) => { let mut mt = ast_mt_to_mt(self, rscope, mt); if a_seq_ty.mutbl == ast::m_mutbl || a_seq_ty.mutbl == ast::m_const { mt = ty::mt { ty: mt.ty, mutbl: a_seq_ty.mutbl }; } return ty::mk_evec(tcx, mt, vst); } ast::ty_path(path, id) if a_seq_ty.mutbl == ast::m_imm => { match tcx.def_map.find(&id) { Some(&ast::def_prim_ty(ast::ty_str)) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); return ty::mk_estr(tcx, vst); } Some(&ast::def_ty(type_def_id)) => { let result = ast_path_to_substs_and_ty( self, rscope, type_def_id, path); match ty::get(result.ty).sty { ty::ty_trait(trait_def_id, ref substs, _) => { let trait_store = match vst { ty::vstore_box => ty::BoxTraitStore, ty::vstore_uniq => ty::UniqTraitStore, ty::vstore_slice(r) => { ty::RegionTraitStore(r) } ty::vstore_fixed(*) => { tcx.sess.span_err( path.span, ~"@trait, ~trait or &trait \ are the only supported \ forms of casting-to-\ trait"); ty::BoxTraitStore } }; return ty::mk_trait(tcx, trait_def_id, /*bad*/copy *substs, trait_store); } _ => {} } } _ => {} } } _ => {} } let seq_ty = ast_mt_to_mt(self, rscope, a_seq_ty); return constr(seq_ty); } fn check_path_args(tcx: ty::ctxt, path: @ast::path, flags: uint) { if (flags & NO_TPS) != 0u { if path.types.len() > 0u { tcx.sess.span_err( path.span, ~"type parameters are not allowed on this type"); } } if (flags & NO_REGIONS) != 0u { if path.rp.is_some() { tcx.sess.span_err( path.span, ~"region parameters are not allowed on this type"); } } } let tcx = self.tcx(); match tcx.ast_ty_to_ty_cache.find(&ast_ty.id) { Some(&ty::atttce_resolved(ty)) => return ty, Some(&ty::atttce_unresolved) => { tcx.sess.span_fatal(ast_ty.span, ~"illegal recursive type; \ insert an enum in the cycle, \ if this is desired"); } None => { /* go on */ } } tcx.ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_unresolved); let typ = match ast_ty.node { ast::ty_nil => ty::mk_nil(tcx), ast::ty_bot => ty::mk_bot(tcx), ast::ty_box(ref mt) => { mk_pointer(self, rscope, mt, ty::vstore_box, |tmt| ty::mk_box(tcx, tmt)) } ast::ty_uniq(ref mt) => { mk_pointer(self, rscope, mt, ty::vstore_uniq, |tmt| ty::mk_uniq(tcx, tmt)) } ast::ty_vec(ref mt) => { tcx.sess.span_err(ast_ty.span, ~"bare `[]` is not a type"); // return /something/ so they can at least get more errors ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, mt), ty::vstore_uniq) } ast::ty_ptr(ref mt) => { ty::mk_ptr(tcx, ast_mt_to_mt(self, rscope, mt)) } ast::ty_rptr(region, ref mt) => { let r = ast_region_to_region(self, rscope, ast_ty.span, region); mk_pointer(self, rscope, mt, ty::vstore_slice(r), |tmt| ty::mk_rptr(tcx, r, tmt)) } ast::ty_tup(ref fields) => { let flds = fields.map(|t| ast_ty_to_ty(self, rscope, *t)); ty::mk_tup(tcx, flds) } ast::ty_bare_fn(ref bf) => { ty::mk_bare_fn(tcx, ty_of_bare_fn(self, rscope, bf.purity, bf.abis, &bf.lifetimes, &bf.decl)) } ast::ty_closure(ref f) => { let fn_decl = ty_of_closure(self, rscope, f.sigil, f.purity, f.onceness, f.region, &f.decl, None, &f.lifetimes, ast_ty.span); ty::mk_closure(tcx, fn_decl) } ast::ty_path(path, id) => { let a_def = match tcx.def_map.find(&id) { None => tcx.sess.span_fatal( ast_ty.span, fmt!("unbound path %s", path_to_str(path, tcx.sess.intr()))), Some(&d) => d }; match a_def { ast::def_ty(did) | ast::def_struct(did) => { ast_path_to_ty(self, rscope, did, path).ty } ast::def_prim_ty(nty) => { match nty { ast::ty_bool => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_bool(tcx) } ast::ty_int(it) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_mach_int(tcx, it) } ast::ty_uint(uit) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_mach_uint(tcx, uit) } ast::ty_float(ft) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_mach_float(tcx, ft) } ast::ty_str => { tcx.sess.span_err(ast_ty.span, ~"bare `str` is not a type"); // return /something/ so they can at least get more errors ty::mk_estr(tcx, ty::vstore_uniq) } } } ast::def_ty_param(id, n) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_param(tcx, n, id) } ast::def_self_ty(id) => { // n.b.: resolve guarantees that the self type only appears in a // trait, which we rely upon in various places when creating // substs check_path_args(tcx, path, NO_TPS | NO_REGIONS); let did = ast_util::local_def(id); ty::mk_self(tcx, did) } _ => { tcx.sess.span_fatal(ast_ty.span, ~"found type name used as a variable"); } } } ast::ty_fixed_length_vec(ref a_mt, e) => { match const_eval::eval_const_expr_partial(tcx, e) { Ok(ref r) => { match *r { const_eval::const_int(i) => ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt), ty::vstore_fixed(i as uint)), const_eval::const_uint(i) => ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt), ty::vstore_fixed(i as uint)), _ => { tcx.sess.span_fatal( ast_ty.span, ~"expected constant expr for vector length"); } } } Err(ref r) => { tcx.sess.span_fatal( ast_ty.span, fmt!("expected constant expr for vector length: %s", *r)); } } } ast::ty_infer => { // ty_infer should only appear as the type of arguments or return // values in a fn_expr, or as the type of local variables. Both of // these cases are handled specially and should not descend into this // routine. self.tcx().sess.span_bug( ast_ty.span, ~"found `ty_infer` in unexpected place"); } ast::ty_mac(_) => { tcx.sess.span_bug(ast_ty.span, ~"found `ty_mac` in unexpected place"); } }; tcx.ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_resolved(typ)); return typ; } pub fn ty_of_arg<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, a: ast::arg, expected_ty: Option<ty::arg>) -> ty::arg { let ty = match a.ty.node { ast::ty_infer if expected_ty.is_some() => expected_ty.get().ty, ast::ty_infer => self.ty_infer(a.ty.span), _ => ast_ty_to_ty(self, rscope, a.ty) }; let mode = { match a.mode { ast::infer(_) if expected_ty.is_some() => { result::get(&ty::unify_mode( self.tcx(), ty::expected_found {expected: expected_ty.get().mode, found: a.mode})) } ast::infer(_) => { match ty::get(ty).sty { // If the type is not specified, then this must be a fn expr. // Leave the mode as infer(_), it will get inferred based // on constraints elsewhere. ty::ty_infer(_) => a.mode, // If the type is known, then use the default for that type. // Here we unify m and the default. This should update the // tables in tcx but should never fail, because nothing else // will have been unified with m yet: _ => { let m1 = ast::expl(ty::default_arg_mode_for_ty(self.tcx(), ty)); result::get(&ty::unify_mode( self.tcx(), ty::expected_found {expected: m1, found: a.mode})) } } } ast::expl(_) => a.mode } }; arg {mode: mode, ty: ty} } pub fn bound_lifetimes<AC:AstConv>( self: &AC, ast_lifetimes: &OptVec<ast::Lifetime>) -> OptVec<ast::ident> { /*! * * Converts a list of lifetimes into a list of bound identifier * names. Does not permit special names like 'static or 'self to * be bound. Note that this function is for use in closures, * methods, and fn definitions. It is legal to bind 'self in a * type. Eventually this distinction should go away and the same * rules should apply everywhere ('self would not be a special name * at that point). */ let special_idents = [special_idents::static, special_idents::self_]; let mut bound_lifetime_names = opt_vec::Empty; ast_lifetimes.map_to_vec(|ast_lifetime| { if special_idents.any(|&i| i == ast_lifetime.ident) { self.tcx().sess.span_err( ast_lifetime.span, fmt!("illegal lifetime parameter name: `%s`", lifetime_to_str(ast_lifetime, self.tcx().sess.intr()))); } else { bound_lifetime_names.push(ast_lifetime.ident); } }); bound_lifetime_names } pub fn ty_of_bare_fn<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, purity: ast::purity, abi: AbiSet, lifetimes: &OptVec<ast::Lifetime>, decl: &ast::fn_decl) -> ty::BareFnTy { debug!("ty_of_bare_fn"); // new region names that appear inside of the fn decl are bound to // that function type let bound_lifetime_names = bound_lifetimes(self, lifetimes); let rb = in_binding_rscope(rscope, RegionParamNames(copy bound_lifetime_names)); let input_tys = decl.inputs.map(|a| ty_of_arg(self, &rb, *a, None)); let output_ty = match decl.output.node { ast::ty_infer => self.ty_infer(decl.output.span), _ => ast_ty_to_ty(self, &rb, decl.output) }; ty::BareFnTy { purity: purity, abis: abi, sig: ty::FnSig {bound_lifetime_names: bound_lifetime_names, inputs: input_tys, output: output_ty} } } pub fn ty_of_closure<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, sigil: ast::Sigil, purity: ast::purity, onceness: ast::Onceness, opt_lifetime: Option<@ast::Lifetime>, decl: &ast::fn_decl, expected_sig: Option<ty::FnSig>, lifetimes: &OptVec<ast::Lifetime>, span: span) -> ty::ClosureTy { // The caller should not both provide explicit bound lifetime // names and expected types. Either we infer the bound lifetime // names or they are provided, but not both. assert!(lifetimes.is_empty() || expected_sig.is_none()); debug!("ty_of_fn_decl"); let _i = indenter(); // resolve the function bound region in the original region // scope `rscope`, not the scope of the function parameters let bound_region = match opt_lifetime { Some(_) => { ast_region_to_region(self, rscope, span, opt_lifetime) } None => { match sigil { ast::OwnedSigil | ast::ManagedSigil => { // @fn(), ~fn() default to static as the bound // on their upvars: ty::re_static } ast::BorrowedSigil => { // &fn() defaults as normal for an omitted lifetime: ast_region_to_region(self, rscope, span, opt_lifetime) } } } }; // new region names that appear inside of the fn decl are bound to // that function type let bound_lifetime_names = bound_lifetimes(self, lifetimes); let rb = in_binding_rscope(rscope, RegionParamNames(copy bound_lifetime_names)); let input_tys = do decl.inputs.mapi |i, a| { let expected_arg_ty = do expected_sig.chain_ref |e| { // no guarantee that the correct number of expected args // were supplied if i < e.inputs.len() {Some(e.inputs[i])} else {None} }; ty_of_arg(self, &rb, *a, expected_arg_ty) }; let expected_ret_ty = expected_sig.map(|e| e.output); let output_ty = match decl.output.node { ast::ty_infer if expected_ret_ty.is_some() => expected_ret_ty.get(), ast::ty_infer => self.ty_infer(decl.output.span), _ => ast_ty_to_ty(self, &rb, decl.output) }; ty::ClosureTy { purity: purity, sigil: sigil, onceness: onceness, region: bound_region, sig: ty::FnSig {bound_lifetime_names: bound_lifetime_names, inputs: input_tys, output: output_ty} } }
{ // Look up the polytype of the item and then substitute the provided types // for any type/region parameters. let ty::ty_param_substs_and_ty { substs: substs, ty: ty } = ast_path_to_substs_and_ty(self, rscope, did, path); ty_param_substs_and_ty { substs: substs, ty: ty } }
identifier_body
astconv.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * Conversion from AST representation of types to the ty.rs * representation. The main routine here is `ast_ty_to_ty()`: each use * is parameterized by an instance of `AstConv` and a `region_scope`. * * The parameterization of `ast_ty_to_ty()` is because it behaves * somewhat differently during the collect and check phases, particularly * with respect to looking up the types of top-level items. In the * collect phase, the crate context is used as the `AstConv` instance; * in this phase, the `get_item_ty()` function triggers a recursive call * to `ty_of_item()` (note that `ast_ty_to_ty()` will detect recursive * types and report an error). In the check phase, when the @FnCtxt is * used as the `AstConv`, `get_item_ty()` just looks up the item type in * `tcx.tcache`. * * The `region_scope` trait controls how region references are * handled. It has two methods which are used to resolve anonymous * region references (e.g., `&T`) and named region references (e.g., * `&a.T`). There are numerous region scopes that can be used, but most * commonly you want either `empty_rscope`, which permits only the static * region, or `type_rscope`, which permits the self region if the type in * question is parameterized by a region. * * Unlike the `AstConv` trait, the region scope can change as we descend * the type. This is to accommodate the fact that (a) fn types are binding * scopes and (b) the default region may change. To understand case (a), * consider something like: * * type foo = { x: &a.int, y: &fn(&a.int) } * * The type of `x` is an error because there is no region `a` in scope. * In the type of `y`, however, region `a` is considered a bound region * as it does not already appear in scope. * * Case (b) says that if you have a type: * type foo<'self> = ...; * type bar = fn(&foo, &a.foo) * The fully expanded version of type bar is: * type bar = fn(&'foo &, &a.foo<'a>) * Note that the self region for the `foo` defaulted to `&` in the first * case but `&a` in the second. Basically, defaults that appear inside * an rptr (`&r.T`) use the region `r` that appears in the rptr. */ use core::prelude::*; use middle::const_eval; use middle::ty::{arg, substs}; use middle::ty::{ty_param_substs_and_ty}; use middle::ty; use middle::typeck::rscope::in_binding_rscope; use middle::typeck::rscope::{region_scope, RegionError}; use middle::typeck::rscope::RegionParamNames; use core::result; use core::vec; use syntax::abi::AbiSet; use syntax::{ast, ast_util}; use syntax::codemap::span; use syntax::opt_vec::OptVec; use syntax::opt_vec; use syntax::print::pprust::{lifetime_to_str, path_to_str}; use syntax::parse::token::special_idents; use util::common::indenter; pub trait AstConv { fn tcx(&self) -> ty::ctxt; fn get_item_ty(&self, id: ast::def_id) -> ty::ty_param_bounds_and_ty; // what type should we use when a type is omitted? fn ty_infer(&self, span: span) -> ty::t; } pub fn
( tcx: ty::ctxt, span: span, a_r: Option<@ast::Lifetime>, res: Result<ty::Region, RegionError>) -> ty::Region { match res { result::Ok(r) => r, result::Err(ref e) => { let descr = match a_r { None => ~"anonymous lifetime", Some(a) => fmt!("lifetime %s", lifetime_to_str(a, tcx.sess.intr())) }; tcx.sess.span_err( span, fmt!("Illegal %s: %s", descr, e.msg)); e.replacement } } } pub fn ast_region_to_region<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, default_span: span, opt_lifetime: Option<@ast::Lifetime>) -> ty::Region { let (span, res) = match opt_lifetime { None => { (default_span, rscope.anon_region(default_span)) } Some(ref lifetime) if lifetime.ident == special_idents::static => { (lifetime.span, Ok(ty::re_static)) } Some(ref lifetime) if lifetime.ident == special_idents::self_ => { (lifetime.span, rscope.self_region(lifetime.span)) } Some(ref lifetime) => { (lifetime.span, rscope.named_region(lifetime.span, lifetime.ident)) } }; get_region_reporting_err(self.tcx(), span, opt_lifetime, res) } pub fn ast_path_to_substs_and_ty<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, did: ast::def_id, path: @ast::path) -> ty_param_substs_and_ty { let tcx = self.tcx(); let ty::ty_param_bounds_and_ty { bounds: decl_bounds, region_param: decl_rp, ty: decl_ty } = self.get_item_ty(did); debug!("ast_path_to_substs_and_ty: did=%? decl_rp=%?", did, decl_rp); // If the type is parameterized by the self region, then replace self // region with the current anon region binding (in other words, // whatever & would get replaced with). let self_r = match (decl_rp, path.rp) { (None, None) => { None } (None, Some(_)) => { tcx.sess.span_err( path.span, fmt!("no region bound is allowed on `%s`, \ which is not declared as containing region pointers", ty::item_path_str(tcx, did))); None } (Some(_), None) => { let res = rscope.anon_region(path.span); let r = get_region_reporting_err(self.tcx(), path.span, None, res); Some(r) } (Some(_), Some(_)) => { Some(ast_region_to_region(self, rscope, path.span, path.rp)) } }; // Convert the type parameters supplied by the user. if !vec::same_length(*decl_bounds, path.types) { self.tcx().sess.span_fatal( path.span, fmt!("wrong number of type arguments: expected %u but found %u", (*decl_bounds).len(), path.types.len())); } let tps = path.types.map(|a_t| ast_ty_to_ty(self, rscope, *a_t)); let substs = substs {self_r:self_r, self_ty:None, tps:tps}; let ty = ty::subst(tcx, &substs, decl_ty); ty_param_substs_and_ty { substs: substs, ty: ty } } pub fn ast_path_to_ty<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, did: ast::def_id, path: @ast::path) -> ty_param_substs_and_ty { // Look up the polytype of the item and then substitute the provided types // for any type/region parameters. let ty::ty_param_substs_and_ty { substs: substs, ty: ty } = ast_path_to_substs_and_ty(self, rscope, did, path); ty_param_substs_and_ty { substs: substs, ty: ty } } pub static NO_REGIONS: uint = 1; pub static NO_TPS: uint = 2; // Parses the programmer's textual representation of a type into our // internal notion of a type. `getter` is a function that returns the type // corresponding to a definition ID: pub fn ast_ty_to_ty<AC:AstConv, RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, &&ast_ty: @ast::Ty) -> ty::t { fn ast_mt_to_mt<AC:AstConv, RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, mt: &ast::mt) -> ty::mt { ty::mt {ty: ast_ty_to_ty(self, rscope, mt.ty), mutbl: mt.mutbl} } // Handle @, ~, and & being able to mean estrs and evecs. // If a_seq_ty is a str or a vec, make it an estr/evec. // Also handle first-class trait types. fn mk_pointer<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, a_seq_ty: &ast::mt, vst: ty::vstore, constr: &fn(ty::mt) -> ty::t) -> ty::t { let tcx = self.tcx(); match a_seq_ty.ty.node { ast::ty_vec(ref mt) => { let mut mt = ast_mt_to_mt(self, rscope, mt); if a_seq_ty.mutbl == ast::m_mutbl || a_seq_ty.mutbl == ast::m_const { mt = ty::mt { ty: mt.ty, mutbl: a_seq_ty.mutbl }; } return ty::mk_evec(tcx, mt, vst); } ast::ty_path(path, id) if a_seq_ty.mutbl == ast::m_imm => { match tcx.def_map.find(&id) { Some(&ast::def_prim_ty(ast::ty_str)) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); return ty::mk_estr(tcx, vst); } Some(&ast::def_ty(type_def_id)) => { let result = ast_path_to_substs_and_ty( self, rscope, type_def_id, path); match ty::get(result.ty).sty { ty::ty_trait(trait_def_id, ref substs, _) => { let trait_store = match vst { ty::vstore_box => ty::BoxTraitStore, ty::vstore_uniq => ty::UniqTraitStore, ty::vstore_slice(r) => { ty::RegionTraitStore(r) } ty::vstore_fixed(*) => { tcx.sess.span_err( path.span, ~"@trait, ~trait or &trait \ are the only supported \ forms of casting-to-\ trait"); ty::BoxTraitStore } }; return ty::mk_trait(tcx, trait_def_id, /*bad*/copy *substs, trait_store); } _ => {} } } _ => {} } } _ => {} } let seq_ty = ast_mt_to_mt(self, rscope, a_seq_ty); return constr(seq_ty); } fn check_path_args(tcx: ty::ctxt, path: @ast::path, flags: uint) { if (flags & NO_TPS) != 0u { if path.types.len() > 0u { tcx.sess.span_err( path.span, ~"type parameters are not allowed on this type"); } } if (flags & NO_REGIONS) != 0u { if path.rp.is_some() { tcx.sess.span_err( path.span, ~"region parameters are not allowed on this type"); } } } let tcx = self.tcx(); match tcx.ast_ty_to_ty_cache.find(&ast_ty.id) { Some(&ty::atttce_resolved(ty)) => return ty, Some(&ty::atttce_unresolved) => { tcx.sess.span_fatal(ast_ty.span, ~"illegal recursive type; \ insert an enum in the cycle, \ if this is desired"); } None => { /* go on */ } } tcx.ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_unresolved); let typ = match ast_ty.node { ast::ty_nil => ty::mk_nil(tcx), ast::ty_bot => ty::mk_bot(tcx), ast::ty_box(ref mt) => { mk_pointer(self, rscope, mt, ty::vstore_box, |tmt| ty::mk_box(tcx, tmt)) } ast::ty_uniq(ref mt) => { mk_pointer(self, rscope, mt, ty::vstore_uniq, |tmt| ty::mk_uniq(tcx, tmt)) } ast::ty_vec(ref mt) => { tcx.sess.span_err(ast_ty.span, ~"bare `[]` is not a type"); // return /something/ so they can at least get more errors ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, mt), ty::vstore_uniq) } ast::ty_ptr(ref mt) => { ty::mk_ptr(tcx, ast_mt_to_mt(self, rscope, mt)) } ast::ty_rptr(region, ref mt) => { let r = ast_region_to_region(self, rscope, ast_ty.span, region); mk_pointer(self, rscope, mt, ty::vstore_slice(r), |tmt| ty::mk_rptr(tcx, r, tmt)) } ast::ty_tup(ref fields) => { let flds = fields.map(|t| ast_ty_to_ty(self, rscope, *t)); ty::mk_tup(tcx, flds) } ast::ty_bare_fn(ref bf) => { ty::mk_bare_fn(tcx, ty_of_bare_fn(self, rscope, bf.purity, bf.abis, &bf.lifetimes, &bf.decl)) } ast::ty_closure(ref f) => { let fn_decl = ty_of_closure(self, rscope, f.sigil, f.purity, f.onceness, f.region, &f.decl, None, &f.lifetimes, ast_ty.span); ty::mk_closure(tcx, fn_decl) } ast::ty_path(path, id) => { let a_def = match tcx.def_map.find(&id) { None => tcx.sess.span_fatal( ast_ty.span, fmt!("unbound path %s", path_to_str(path, tcx.sess.intr()))), Some(&d) => d }; match a_def { ast::def_ty(did) | ast::def_struct(did) => { ast_path_to_ty(self, rscope, did, path).ty } ast::def_prim_ty(nty) => { match nty { ast::ty_bool => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_bool(tcx) } ast::ty_int(it) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_mach_int(tcx, it) } ast::ty_uint(uit) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_mach_uint(tcx, uit) } ast::ty_float(ft) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_mach_float(tcx, ft) } ast::ty_str => { tcx.sess.span_err(ast_ty.span, ~"bare `str` is not a type"); // return /something/ so they can at least get more errors ty::mk_estr(tcx, ty::vstore_uniq) } } } ast::def_ty_param(id, n) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_param(tcx, n, id) } ast::def_self_ty(id) => { // n.b.: resolve guarantees that the self type only appears in a // trait, which we rely upon in various places when creating // substs check_path_args(tcx, path, NO_TPS | NO_REGIONS); let did = ast_util::local_def(id); ty::mk_self(tcx, did) } _ => { tcx.sess.span_fatal(ast_ty.span, ~"found type name used as a variable"); } } } ast::ty_fixed_length_vec(ref a_mt, e) => { match const_eval::eval_const_expr_partial(tcx, e) { Ok(ref r) => { match *r { const_eval::const_int(i) => ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt), ty::vstore_fixed(i as uint)), const_eval::const_uint(i) => ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt), ty::vstore_fixed(i as uint)), _ => { tcx.sess.span_fatal( ast_ty.span, ~"expected constant expr for vector length"); } } } Err(ref r) => { tcx.sess.span_fatal( ast_ty.span, fmt!("expected constant expr for vector length: %s", *r)); } } } ast::ty_infer => { // ty_infer should only appear as the type of arguments or return // values in a fn_expr, or as the type of local variables. Both of // these cases are handled specially and should not descend into this // routine. self.tcx().sess.span_bug( ast_ty.span, ~"found `ty_infer` in unexpected place"); } ast::ty_mac(_) => { tcx.sess.span_bug(ast_ty.span, ~"found `ty_mac` in unexpected place"); } }; tcx.ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_resolved(typ)); return typ; } pub fn ty_of_arg<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, a: ast::arg, expected_ty: Option<ty::arg>) -> ty::arg { let ty = match a.ty.node { ast::ty_infer if expected_ty.is_some() => expected_ty.get().ty, ast::ty_infer => self.ty_infer(a.ty.span), _ => ast_ty_to_ty(self, rscope, a.ty) }; let mode = { match a.mode { ast::infer(_) if expected_ty.is_some() => { result::get(&ty::unify_mode( self.tcx(), ty::expected_found {expected: expected_ty.get().mode, found: a.mode})) } ast::infer(_) => { match ty::get(ty).sty { // If the type is not specified, then this must be a fn expr. // Leave the mode as infer(_), it will get inferred based // on constraints elsewhere. ty::ty_infer(_) => a.mode, // If the type is known, then use the default for that type. // Here we unify m and the default. This should update the // tables in tcx but should never fail, because nothing else // will have been unified with m yet: _ => { let m1 = ast::expl(ty::default_arg_mode_for_ty(self.tcx(), ty)); result::get(&ty::unify_mode( self.tcx(), ty::expected_found {expected: m1, found: a.mode})) } } } ast::expl(_) => a.mode } }; arg {mode: mode, ty: ty} } pub fn bound_lifetimes<AC:AstConv>( self: &AC, ast_lifetimes: &OptVec<ast::Lifetime>) -> OptVec<ast::ident> { /*! * * Converts a list of lifetimes into a list of bound identifier * names. Does not permit special names like 'static or 'self to * be bound. Note that this function is for use in closures, * methods, and fn definitions. It is legal to bind 'self in a * type. Eventually this distinction should go away and the same * rules should apply everywhere ('self would not be a special name * at that point). */ let special_idents = [special_idents::static, special_idents::self_]; let mut bound_lifetime_names = opt_vec::Empty; ast_lifetimes.map_to_vec(|ast_lifetime| { if special_idents.any(|&i| i == ast_lifetime.ident) { self.tcx().sess.span_err( ast_lifetime.span, fmt!("illegal lifetime parameter name: `%s`", lifetime_to_str(ast_lifetime, self.tcx().sess.intr()))); } else { bound_lifetime_names.push(ast_lifetime.ident); } }); bound_lifetime_names } pub fn ty_of_bare_fn<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, purity: ast::purity, abi: AbiSet, lifetimes: &OptVec<ast::Lifetime>, decl: &ast::fn_decl) -> ty::BareFnTy { debug!("ty_of_bare_fn"); // new region names that appear inside of the fn decl are bound to // that function type let bound_lifetime_names = bound_lifetimes(self, lifetimes); let rb = in_binding_rscope(rscope, RegionParamNames(copy bound_lifetime_names)); let input_tys = decl.inputs.map(|a| ty_of_arg(self, &rb, *a, None)); let output_ty = match decl.output.node { ast::ty_infer => self.ty_infer(decl.output.span), _ => ast_ty_to_ty(self, &rb, decl.output) }; ty::BareFnTy { purity: purity, abis: abi, sig: ty::FnSig {bound_lifetime_names: bound_lifetime_names, inputs: input_tys, output: output_ty} } } pub fn ty_of_closure<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, sigil: ast::Sigil, purity: ast::purity, onceness: ast::Onceness, opt_lifetime: Option<@ast::Lifetime>, decl: &ast::fn_decl, expected_sig: Option<ty::FnSig>, lifetimes: &OptVec<ast::Lifetime>, span: span) -> ty::ClosureTy { // The caller should not both provide explicit bound lifetime // names and expected types. Either we infer the bound lifetime // names or they are provided, but not both. assert!(lifetimes.is_empty() || expected_sig.is_none()); debug!("ty_of_fn_decl"); let _i = indenter(); // resolve the function bound region in the original region // scope `rscope`, not the scope of the function parameters let bound_region = match opt_lifetime { Some(_) => { ast_region_to_region(self, rscope, span, opt_lifetime) } None => { match sigil { ast::OwnedSigil | ast::ManagedSigil => { // @fn(), ~fn() default to static as the bound // on their upvars: ty::re_static } ast::BorrowedSigil => { // &fn() defaults as normal for an omitted lifetime: ast_region_to_region(self, rscope, span, opt_lifetime) } } } }; // new region names that appear inside of the fn decl are bound to // that function type let bound_lifetime_names = bound_lifetimes(self, lifetimes); let rb = in_binding_rscope(rscope, RegionParamNames(copy bound_lifetime_names)); let input_tys = do decl.inputs.mapi |i, a| { let expected_arg_ty = do expected_sig.chain_ref |e| { // no guarantee that the correct number of expected args // were supplied if i < e.inputs.len() {Some(e.inputs[i])} else {None} }; ty_of_arg(self, &rb, *a, expected_arg_ty) }; let expected_ret_ty = expected_sig.map(|e| e.output); let output_ty = match decl.output.node { ast::ty_infer if expected_ret_ty.is_some() => expected_ret_ty.get(), ast::ty_infer => self.ty_infer(decl.output.span), _ => ast_ty_to_ty(self, &rb, decl.output) }; ty::ClosureTy { purity: purity, sigil: sigil, onceness: onceness, region: bound_region, sig: ty::FnSig {bound_lifetime_names: bound_lifetime_names, inputs: input_tys, output: output_ty} } }
get_region_reporting_err
identifier_name
astconv.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * Conversion from AST representation of types to the ty.rs * representation. The main routine here is `ast_ty_to_ty()`: each use * is parameterized by an instance of `AstConv` and a `region_scope`. * * The parameterization of `ast_ty_to_ty()` is because it behaves * somewhat differently during the collect and check phases, particularly * with respect to looking up the types of top-level items. In the * collect phase, the crate context is used as the `AstConv` instance; * in this phase, the `get_item_ty()` function triggers a recursive call * to `ty_of_item()` (note that `ast_ty_to_ty()` will detect recursive * types and report an error). In the check phase, when the @FnCtxt is * used as the `AstConv`, `get_item_ty()` just looks up the item type in * `tcx.tcache`. * * The `region_scope` trait controls how region references are * handled. It has two methods which are used to resolve anonymous * region references (e.g., `&T`) and named region references (e.g., * `&a.T`). There are numerous region scopes that can be used, but most * commonly you want either `empty_rscope`, which permits only the static * region, or `type_rscope`, which permits the self region if the type in * question is parameterized by a region. * * Unlike the `AstConv` trait, the region scope can change as we descend * the type. This is to accommodate the fact that (a) fn types are binding * scopes and (b) the default region may change. To understand case (a), * consider something like: * * type foo = { x: &a.int, y: &fn(&a.int) } * * The type of `x` is an error because there is no region `a` in scope. * In the type of `y`, however, region `a` is considered a bound region * as it does not already appear in scope. * * Case (b) says that if you have a type: * type foo<'self> = ...; * type bar = fn(&foo, &a.foo) * The fully expanded version of type bar is: * type bar = fn(&'foo &, &a.foo<'a>) * Note that the self region for the `foo` defaulted to `&` in the first * case but `&a` in the second. Basically, defaults that appear inside * an rptr (`&r.T`) use the region `r` that appears in the rptr. */ use core::prelude::*; use middle::const_eval; use middle::ty::{arg, substs}; use middle::ty::{ty_param_substs_and_ty}; use middle::ty; use middle::typeck::rscope::in_binding_rscope; use middle::typeck::rscope::{region_scope, RegionError}; use middle::typeck::rscope::RegionParamNames; use core::result; use core::vec; use syntax::abi::AbiSet; use syntax::{ast, ast_util}; use syntax::codemap::span; use syntax::opt_vec::OptVec; use syntax::opt_vec; use syntax::print::pprust::{lifetime_to_str, path_to_str}; use syntax::parse::token::special_idents; use util::common::indenter; pub trait AstConv { fn tcx(&self) -> ty::ctxt; fn get_item_ty(&self, id: ast::def_id) -> ty::ty_param_bounds_and_ty; // what type should we use when a type is omitted? fn ty_infer(&self, span: span) -> ty::t; } pub fn get_region_reporting_err( tcx: ty::ctxt, span: span, a_r: Option<@ast::Lifetime>, res: Result<ty::Region, RegionError>) -> ty::Region { match res { result::Ok(r) => r, result::Err(ref e) => { let descr = match a_r { None => ~"anonymous lifetime", Some(a) => fmt!("lifetime %s", lifetime_to_str(a, tcx.sess.intr())) }; tcx.sess.span_err( span, fmt!("Illegal %s: %s", descr, e.msg)); e.replacement } } } pub fn ast_region_to_region<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, default_span: span, opt_lifetime: Option<@ast::Lifetime>) -> ty::Region { let (span, res) = match opt_lifetime { None => { (default_span, rscope.anon_region(default_span)) } Some(ref lifetime) if lifetime.ident == special_idents::static => { (lifetime.span, Ok(ty::re_static)) } Some(ref lifetime) if lifetime.ident == special_idents::self_ => { (lifetime.span, rscope.self_region(lifetime.span)) } Some(ref lifetime) =>
}; get_region_reporting_err(self.tcx(), span, opt_lifetime, res) } pub fn ast_path_to_substs_and_ty<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, did: ast::def_id, path: @ast::path) -> ty_param_substs_and_ty { let tcx = self.tcx(); let ty::ty_param_bounds_and_ty { bounds: decl_bounds, region_param: decl_rp, ty: decl_ty } = self.get_item_ty(did); debug!("ast_path_to_substs_and_ty: did=%? decl_rp=%?", did, decl_rp); // If the type is parameterized by the self region, then replace self // region with the current anon region binding (in other words, // whatever & would get replaced with). let self_r = match (decl_rp, path.rp) { (None, None) => { None } (None, Some(_)) => { tcx.sess.span_err( path.span, fmt!("no region bound is allowed on `%s`, \ which is not declared as containing region pointers", ty::item_path_str(tcx, did))); None } (Some(_), None) => { let res = rscope.anon_region(path.span); let r = get_region_reporting_err(self.tcx(), path.span, None, res); Some(r) } (Some(_), Some(_)) => { Some(ast_region_to_region(self, rscope, path.span, path.rp)) } }; // Convert the type parameters supplied by the user. if !vec::same_length(*decl_bounds, path.types) { self.tcx().sess.span_fatal( path.span, fmt!("wrong number of type arguments: expected %u but found %u", (*decl_bounds).len(), path.types.len())); } let tps = path.types.map(|a_t| ast_ty_to_ty(self, rscope, *a_t)); let substs = substs {self_r:self_r, self_ty:None, tps:tps}; let ty = ty::subst(tcx, &substs, decl_ty); ty_param_substs_and_ty { substs: substs, ty: ty } } pub fn ast_path_to_ty<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, did: ast::def_id, path: @ast::path) -> ty_param_substs_and_ty { // Look up the polytype of the item and then substitute the provided types // for any type/region parameters. let ty::ty_param_substs_and_ty { substs: substs, ty: ty } = ast_path_to_substs_and_ty(self, rscope, did, path); ty_param_substs_and_ty { substs: substs, ty: ty } } pub static NO_REGIONS: uint = 1; pub static NO_TPS: uint = 2; // Parses the programmer's textual representation of a type into our // internal notion of a type. `getter` is a function that returns the type // corresponding to a definition ID: pub fn ast_ty_to_ty<AC:AstConv, RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, &&ast_ty: @ast::Ty) -> ty::t { fn ast_mt_to_mt<AC:AstConv, RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, mt: &ast::mt) -> ty::mt { ty::mt {ty: ast_ty_to_ty(self, rscope, mt.ty), mutbl: mt.mutbl} } // Handle @, ~, and & being able to mean estrs and evecs. // If a_seq_ty is a str or a vec, make it an estr/evec. // Also handle first-class trait types. fn mk_pointer<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, a_seq_ty: &ast::mt, vst: ty::vstore, constr: &fn(ty::mt) -> ty::t) -> ty::t { let tcx = self.tcx(); match a_seq_ty.ty.node { ast::ty_vec(ref mt) => { let mut mt = ast_mt_to_mt(self, rscope, mt); if a_seq_ty.mutbl == ast::m_mutbl || a_seq_ty.mutbl == ast::m_const { mt = ty::mt { ty: mt.ty, mutbl: a_seq_ty.mutbl }; } return ty::mk_evec(tcx, mt, vst); } ast::ty_path(path, id) if a_seq_ty.mutbl == ast::m_imm => { match tcx.def_map.find(&id) { Some(&ast::def_prim_ty(ast::ty_str)) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); return ty::mk_estr(tcx, vst); } Some(&ast::def_ty(type_def_id)) => { let result = ast_path_to_substs_and_ty( self, rscope, type_def_id, path); match ty::get(result.ty).sty { ty::ty_trait(trait_def_id, ref substs, _) => { let trait_store = match vst { ty::vstore_box => ty::BoxTraitStore, ty::vstore_uniq => ty::UniqTraitStore, ty::vstore_slice(r) => { ty::RegionTraitStore(r) } ty::vstore_fixed(*) => { tcx.sess.span_err( path.span, ~"@trait, ~trait or &trait \ are the only supported \ forms of casting-to-\ trait"); ty::BoxTraitStore } }; return ty::mk_trait(tcx, trait_def_id, /*bad*/copy *substs, trait_store); } _ => {} } } _ => {} } } _ => {} } let seq_ty = ast_mt_to_mt(self, rscope, a_seq_ty); return constr(seq_ty); } fn check_path_args(tcx: ty::ctxt, path: @ast::path, flags: uint) { if (flags & NO_TPS) != 0u { if path.types.len() > 0u { tcx.sess.span_err( path.span, ~"type parameters are not allowed on this type"); } } if (flags & NO_REGIONS) != 0u { if path.rp.is_some() { tcx.sess.span_err( path.span, ~"region parameters are not allowed on this type"); } } } let tcx = self.tcx(); match tcx.ast_ty_to_ty_cache.find(&ast_ty.id) { Some(&ty::atttce_resolved(ty)) => return ty, Some(&ty::atttce_unresolved) => { tcx.sess.span_fatal(ast_ty.span, ~"illegal recursive type; \ insert an enum in the cycle, \ if this is desired"); } None => { /* go on */ } } tcx.ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_unresolved); let typ = match ast_ty.node { ast::ty_nil => ty::mk_nil(tcx), ast::ty_bot => ty::mk_bot(tcx), ast::ty_box(ref mt) => { mk_pointer(self, rscope, mt, ty::vstore_box, |tmt| ty::mk_box(tcx, tmt)) } ast::ty_uniq(ref mt) => { mk_pointer(self, rscope, mt, ty::vstore_uniq, |tmt| ty::mk_uniq(tcx, tmt)) } ast::ty_vec(ref mt) => { tcx.sess.span_err(ast_ty.span, ~"bare `[]` is not a type"); // return /something/ so they can at least get more errors ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, mt), ty::vstore_uniq) } ast::ty_ptr(ref mt) => { ty::mk_ptr(tcx, ast_mt_to_mt(self, rscope, mt)) } ast::ty_rptr(region, ref mt) => { let r = ast_region_to_region(self, rscope, ast_ty.span, region); mk_pointer(self, rscope, mt, ty::vstore_slice(r), |tmt| ty::mk_rptr(tcx, r, tmt)) } ast::ty_tup(ref fields) => { let flds = fields.map(|t| ast_ty_to_ty(self, rscope, *t)); ty::mk_tup(tcx, flds) } ast::ty_bare_fn(ref bf) => { ty::mk_bare_fn(tcx, ty_of_bare_fn(self, rscope, bf.purity, bf.abis, &bf.lifetimes, &bf.decl)) } ast::ty_closure(ref f) => { let fn_decl = ty_of_closure(self, rscope, f.sigil, f.purity, f.onceness, f.region, &f.decl, None, &f.lifetimes, ast_ty.span); ty::mk_closure(tcx, fn_decl) } ast::ty_path(path, id) => { let a_def = match tcx.def_map.find(&id) { None => tcx.sess.span_fatal( ast_ty.span, fmt!("unbound path %s", path_to_str(path, tcx.sess.intr()))), Some(&d) => d }; match a_def { ast::def_ty(did) | ast::def_struct(did) => { ast_path_to_ty(self, rscope, did, path).ty } ast::def_prim_ty(nty) => { match nty { ast::ty_bool => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_bool(tcx) } ast::ty_int(it) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_mach_int(tcx, it) } ast::ty_uint(uit) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_mach_uint(tcx, uit) } ast::ty_float(ft) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_mach_float(tcx, ft) } ast::ty_str => { tcx.sess.span_err(ast_ty.span, ~"bare `str` is not a type"); // return /something/ so they can at least get more errors ty::mk_estr(tcx, ty::vstore_uniq) } } } ast::def_ty_param(id, n) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_param(tcx, n, id) } ast::def_self_ty(id) => { // n.b.: resolve guarantees that the self type only appears in a // trait, which we rely upon in various places when creating // substs check_path_args(tcx, path, NO_TPS | NO_REGIONS); let did = ast_util::local_def(id); ty::mk_self(tcx, did) } _ => { tcx.sess.span_fatal(ast_ty.span, ~"found type name used as a variable"); } } } ast::ty_fixed_length_vec(ref a_mt, e) => { match const_eval::eval_const_expr_partial(tcx, e) { Ok(ref r) => { match *r { const_eval::const_int(i) => ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt), ty::vstore_fixed(i as uint)), const_eval::const_uint(i) => ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt), ty::vstore_fixed(i as uint)), _ => { tcx.sess.span_fatal( ast_ty.span, ~"expected constant expr for vector length"); } } } Err(ref r) => { tcx.sess.span_fatal( ast_ty.span, fmt!("expected constant expr for vector length: %s", *r)); } } } ast::ty_infer => { // ty_infer should only appear as the type of arguments or return // values in a fn_expr, or as the type of local variables. Both of // these cases are handled specially and should not descend into this // routine. self.tcx().sess.span_bug( ast_ty.span, ~"found `ty_infer` in unexpected place"); } ast::ty_mac(_) => { tcx.sess.span_bug(ast_ty.span, ~"found `ty_mac` in unexpected place"); } }; tcx.ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_resolved(typ)); return typ; } pub fn ty_of_arg<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, a: ast::arg, expected_ty: Option<ty::arg>) -> ty::arg { let ty = match a.ty.node { ast::ty_infer if expected_ty.is_some() => expected_ty.get().ty, ast::ty_infer => self.ty_infer(a.ty.span), _ => ast_ty_to_ty(self, rscope, a.ty) }; let mode = { match a.mode { ast::infer(_) if expected_ty.is_some() => { result::get(&ty::unify_mode( self.tcx(), ty::expected_found {expected: expected_ty.get().mode, found: a.mode})) } ast::infer(_) => { match ty::get(ty).sty { // If the type is not specified, then this must be a fn expr. // Leave the mode as infer(_), it will get inferred based // on constraints elsewhere. ty::ty_infer(_) => a.mode, // If the type is known, then use the default for that type. // Here we unify m and the default. This should update the // tables in tcx but should never fail, because nothing else // will have been unified with m yet: _ => { let m1 = ast::expl(ty::default_arg_mode_for_ty(self.tcx(), ty)); result::get(&ty::unify_mode( self.tcx(), ty::expected_found {expected: m1, found: a.mode})) } } } ast::expl(_) => a.mode } }; arg {mode: mode, ty: ty} } pub fn bound_lifetimes<AC:AstConv>( self: &AC, ast_lifetimes: &OptVec<ast::Lifetime>) -> OptVec<ast::ident> { /*! * * Converts a list of lifetimes into a list of bound identifier * names. Does not permit special names like 'static or 'self to * be bound. Note that this function is for use in closures, * methods, and fn definitions. It is legal to bind 'self in a * type. Eventually this distinction should go away and the same * rules should apply everywhere ('self would not be a special name * at that point). */ let special_idents = [special_idents::static, special_idents::self_]; let mut bound_lifetime_names = opt_vec::Empty; ast_lifetimes.map_to_vec(|ast_lifetime| { if special_idents.any(|&i| i == ast_lifetime.ident) { self.tcx().sess.span_err( ast_lifetime.span, fmt!("illegal lifetime parameter name: `%s`", lifetime_to_str(ast_lifetime, self.tcx().sess.intr()))); } else { bound_lifetime_names.push(ast_lifetime.ident); } }); bound_lifetime_names } pub fn ty_of_bare_fn<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, purity: ast::purity, abi: AbiSet, lifetimes: &OptVec<ast::Lifetime>, decl: &ast::fn_decl) -> ty::BareFnTy { debug!("ty_of_bare_fn"); // new region names that appear inside of the fn decl are bound to // that function type let bound_lifetime_names = bound_lifetimes(self, lifetimes); let rb = in_binding_rscope(rscope, RegionParamNames(copy bound_lifetime_names)); let input_tys = decl.inputs.map(|a| ty_of_arg(self, &rb, *a, None)); let output_ty = match decl.output.node { ast::ty_infer => self.ty_infer(decl.output.span), _ => ast_ty_to_ty(self, &rb, decl.output) }; ty::BareFnTy { purity: purity, abis: abi, sig: ty::FnSig {bound_lifetime_names: bound_lifetime_names, inputs: input_tys, output: output_ty} } } pub fn ty_of_closure<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, sigil: ast::Sigil, purity: ast::purity, onceness: ast::Onceness, opt_lifetime: Option<@ast::Lifetime>, decl: &ast::fn_decl, expected_sig: Option<ty::FnSig>, lifetimes: &OptVec<ast::Lifetime>, span: span) -> ty::ClosureTy { // The caller should not both provide explicit bound lifetime // names and expected types. Either we infer the bound lifetime // names or they are provided, but not both. assert!(lifetimes.is_empty() || expected_sig.is_none()); debug!("ty_of_fn_decl"); let _i = indenter(); // resolve the function bound region in the original region // scope `rscope`, not the scope of the function parameters let bound_region = match opt_lifetime { Some(_) => { ast_region_to_region(self, rscope, span, opt_lifetime) } None => { match sigil { ast::OwnedSigil | ast::ManagedSigil => { // @fn(), ~fn() default to static as the bound // on their upvars: ty::re_static } ast::BorrowedSigil => { // &fn() defaults as normal for an omitted lifetime: ast_region_to_region(self, rscope, span, opt_lifetime) } } } }; // new region names that appear inside of the fn decl are bound to // that function type let bound_lifetime_names = bound_lifetimes(self, lifetimes); let rb = in_binding_rscope(rscope, RegionParamNames(copy bound_lifetime_names)); let input_tys = do decl.inputs.mapi |i, a| { let expected_arg_ty = do expected_sig.chain_ref |e| { // no guarantee that the correct number of expected args // were supplied if i < e.inputs.len() {Some(e.inputs[i])} else {None} }; ty_of_arg(self, &rb, *a, expected_arg_ty) }; let expected_ret_ty = expected_sig.map(|e| e.output); let output_ty = match decl.output.node { ast::ty_infer if expected_ret_ty.is_some() => expected_ret_ty.get(), ast::ty_infer => self.ty_infer(decl.output.span), _ => ast_ty_to_ty(self, &rb, decl.output) }; ty::ClosureTy { purity: purity, sigil: sigil, onceness: onceness, region: bound_region, sig: ty::FnSig {bound_lifetime_names: bound_lifetime_names, inputs: input_tys, output: output_ty} } }
{ (lifetime.span, rscope.named_region(lifetime.span, lifetime.ident)) }
conditional_block
astconv.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * Conversion from AST representation of types to the ty.rs * representation. The main routine here is `ast_ty_to_ty()`: each use * is parameterized by an instance of `AstConv` and a `region_scope`. * * The parameterization of `ast_ty_to_ty()` is because it behaves * somewhat differently during the collect and check phases, particularly * with respect to looking up the types of top-level items. In the * collect phase, the crate context is used as the `AstConv` instance; * in this phase, the `get_item_ty()` function triggers a recursive call * to `ty_of_item()` (note that `ast_ty_to_ty()` will detect recursive * types and report an error). In the check phase, when the @FnCtxt is * used as the `AstConv`, `get_item_ty()` just looks up the item type in * `tcx.tcache`. * * The `region_scope` trait controls how region references are * handled. It has two methods which are used to resolve anonymous * region references (e.g., `&T`) and named region references (e.g., * `&a.T`). There are numerous region scopes that can be used, but most * commonly you want either `empty_rscope`, which permits only the static * region, or `type_rscope`, which permits the self region if the type in * question is parameterized by a region. * * Unlike the `AstConv` trait, the region scope can change as we descend * the type. This is to accommodate the fact that (a) fn types are binding * scopes and (b) the default region may change. To understand case (a), * consider something like: * * type foo = { x: &a.int, y: &fn(&a.int) } * * The type of `x` is an error because there is no region `a` in scope. * In the type of `y`, however, region `a` is considered a bound region * as it does not already appear in scope. *
* Note that the self region for the `foo` defaulted to `&` in the first * case but `&a` in the second. Basically, defaults that appear inside * an rptr (`&r.T`) use the region `r` that appears in the rptr. */ use core::prelude::*; use middle::const_eval; use middle::ty::{arg, substs}; use middle::ty::{ty_param_substs_and_ty}; use middle::ty; use middle::typeck::rscope::in_binding_rscope; use middle::typeck::rscope::{region_scope, RegionError}; use middle::typeck::rscope::RegionParamNames; use core::result; use core::vec; use syntax::abi::AbiSet; use syntax::{ast, ast_util}; use syntax::codemap::span; use syntax::opt_vec::OptVec; use syntax::opt_vec; use syntax::print::pprust::{lifetime_to_str, path_to_str}; use syntax::parse::token::special_idents; use util::common::indenter; pub trait AstConv { fn tcx(&self) -> ty::ctxt; fn get_item_ty(&self, id: ast::def_id) -> ty::ty_param_bounds_and_ty; // what type should we use when a type is omitted? fn ty_infer(&self, span: span) -> ty::t; } pub fn get_region_reporting_err( tcx: ty::ctxt, span: span, a_r: Option<@ast::Lifetime>, res: Result<ty::Region, RegionError>) -> ty::Region { match res { result::Ok(r) => r, result::Err(ref e) => { let descr = match a_r { None => ~"anonymous lifetime", Some(a) => fmt!("lifetime %s", lifetime_to_str(a, tcx.sess.intr())) }; tcx.sess.span_err( span, fmt!("Illegal %s: %s", descr, e.msg)); e.replacement } } } pub fn ast_region_to_region<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, default_span: span, opt_lifetime: Option<@ast::Lifetime>) -> ty::Region { let (span, res) = match opt_lifetime { None => { (default_span, rscope.anon_region(default_span)) } Some(ref lifetime) if lifetime.ident == special_idents::static => { (lifetime.span, Ok(ty::re_static)) } Some(ref lifetime) if lifetime.ident == special_idents::self_ => { (lifetime.span, rscope.self_region(lifetime.span)) } Some(ref lifetime) => { (lifetime.span, rscope.named_region(lifetime.span, lifetime.ident)) } }; get_region_reporting_err(self.tcx(), span, opt_lifetime, res) } pub fn ast_path_to_substs_and_ty<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, did: ast::def_id, path: @ast::path) -> ty_param_substs_and_ty { let tcx = self.tcx(); let ty::ty_param_bounds_and_ty { bounds: decl_bounds, region_param: decl_rp, ty: decl_ty } = self.get_item_ty(did); debug!("ast_path_to_substs_and_ty: did=%? decl_rp=%?", did, decl_rp); // If the type is parameterized by the self region, then replace self // region with the current anon region binding (in other words, // whatever & would get replaced with). let self_r = match (decl_rp, path.rp) { (None, None) => { None } (None, Some(_)) => { tcx.sess.span_err( path.span, fmt!("no region bound is allowed on `%s`, \ which is not declared as containing region pointers", ty::item_path_str(tcx, did))); None } (Some(_), None) => { let res = rscope.anon_region(path.span); let r = get_region_reporting_err(self.tcx(), path.span, None, res); Some(r) } (Some(_), Some(_)) => { Some(ast_region_to_region(self, rscope, path.span, path.rp)) } }; // Convert the type parameters supplied by the user. if !vec::same_length(*decl_bounds, path.types) { self.tcx().sess.span_fatal( path.span, fmt!("wrong number of type arguments: expected %u but found %u", (*decl_bounds).len(), path.types.len())); } let tps = path.types.map(|a_t| ast_ty_to_ty(self, rscope, *a_t)); let substs = substs {self_r:self_r, self_ty:None, tps:tps}; let ty = ty::subst(tcx, &substs, decl_ty); ty_param_substs_and_ty { substs: substs, ty: ty } } pub fn ast_path_to_ty<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, did: ast::def_id, path: @ast::path) -> ty_param_substs_and_ty { // Look up the polytype of the item and then substitute the provided types // for any type/region parameters. let ty::ty_param_substs_and_ty { substs: substs, ty: ty } = ast_path_to_substs_and_ty(self, rscope, did, path); ty_param_substs_and_ty { substs: substs, ty: ty } } pub static NO_REGIONS: uint = 1; pub static NO_TPS: uint = 2; // Parses the programmer's textual representation of a type into our // internal notion of a type. `getter` is a function that returns the type // corresponding to a definition ID: pub fn ast_ty_to_ty<AC:AstConv, RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, &&ast_ty: @ast::Ty) -> ty::t { fn ast_mt_to_mt<AC:AstConv, RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, mt: &ast::mt) -> ty::mt { ty::mt {ty: ast_ty_to_ty(self, rscope, mt.ty), mutbl: mt.mutbl} } // Handle @, ~, and & being able to mean estrs and evecs. // If a_seq_ty is a str or a vec, make it an estr/evec. // Also handle first-class trait types. fn mk_pointer<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, a_seq_ty: &ast::mt, vst: ty::vstore, constr: &fn(ty::mt) -> ty::t) -> ty::t { let tcx = self.tcx(); match a_seq_ty.ty.node { ast::ty_vec(ref mt) => { let mut mt = ast_mt_to_mt(self, rscope, mt); if a_seq_ty.mutbl == ast::m_mutbl || a_seq_ty.mutbl == ast::m_const { mt = ty::mt { ty: mt.ty, mutbl: a_seq_ty.mutbl }; } return ty::mk_evec(tcx, mt, vst); } ast::ty_path(path, id) if a_seq_ty.mutbl == ast::m_imm => { match tcx.def_map.find(&id) { Some(&ast::def_prim_ty(ast::ty_str)) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); return ty::mk_estr(tcx, vst); } Some(&ast::def_ty(type_def_id)) => { let result = ast_path_to_substs_and_ty( self, rscope, type_def_id, path); match ty::get(result.ty).sty { ty::ty_trait(trait_def_id, ref substs, _) => { let trait_store = match vst { ty::vstore_box => ty::BoxTraitStore, ty::vstore_uniq => ty::UniqTraitStore, ty::vstore_slice(r) => { ty::RegionTraitStore(r) } ty::vstore_fixed(*) => { tcx.sess.span_err( path.span, ~"@trait, ~trait or &trait \ are the only supported \ forms of casting-to-\ trait"); ty::BoxTraitStore } }; return ty::mk_trait(tcx, trait_def_id, /*bad*/copy *substs, trait_store); } _ => {} } } _ => {} } } _ => {} } let seq_ty = ast_mt_to_mt(self, rscope, a_seq_ty); return constr(seq_ty); } fn check_path_args(tcx: ty::ctxt, path: @ast::path, flags: uint) { if (flags & NO_TPS) != 0u { if path.types.len() > 0u { tcx.sess.span_err( path.span, ~"type parameters are not allowed on this type"); } } if (flags & NO_REGIONS) != 0u { if path.rp.is_some() { tcx.sess.span_err( path.span, ~"region parameters are not allowed on this type"); } } } let tcx = self.tcx(); match tcx.ast_ty_to_ty_cache.find(&ast_ty.id) { Some(&ty::atttce_resolved(ty)) => return ty, Some(&ty::atttce_unresolved) => { tcx.sess.span_fatal(ast_ty.span, ~"illegal recursive type; \ insert an enum in the cycle, \ if this is desired"); } None => { /* go on */ } } tcx.ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_unresolved); let typ = match ast_ty.node { ast::ty_nil => ty::mk_nil(tcx), ast::ty_bot => ty::mk_bot(tcx), ast::ty_box(ref mt) => { mk_pointer(self, rscope, mt, ty::vstore_box, |tmt| ty::mk_box(tcx, tmt)) } ast::ty_uniq(ref mt) => { mk_pointer(self, rscope, mt, ty::vstore_uniq, |tmt| ty::mk_uniq(tcx, tmt)) } ast::ty_vec(ref mt) => { tcx.sess.span_err(ast_ty.span, ~"bare `[]` is not a type"); // return /something/ so they can at least get more errors ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, mt), ty::vstore_uniq) } ast::ty_ptr(ref mt) => { ty::mk_ptr(tcx, ast_mt_to_mt(self, rscope, mt)) } ast::ty_rptr(region, ref mt) => { let r = ast_region_to_region(self, rscope, ast_ty.span, region); mk_pointer(self, rscope, mt, ty::vstore_slice(r), |tmt| ty::mk_rptr(tcx, r, tmt)) } ast::ty_tup(ref fields) => { let flds = fields.map(|t| ast_ty_to_ty(self, rscope, *t)); ty::mk_tup(tcx, flds) } ast::ty_bare_fn(ref bf) => { ty::mk_bare_fn(tcx, ty_of_bare_fn(self, rscope, bf.purity, bf.abis, &bf.lifetimes, &bf.decl)) } ast::ty_closure(ref f) => { let fn_decl = ty_of_closure(self, rscope, f.sigil, f.purity, f.onceness, f.region, &f.decl, None, &f.lifetimes, ast_ty.span); ty::mk_closure(tcx, fn_decl) } ast::ty_path(path, id) => { let a_def = match tcx.def_map.find(&id) { None => tcx.sess.span_fatal( ast_ty.span, fmt!("unbound path %s", path_to_str(path, tcx.sess.intr()))), Some(&d) => d }; match a_def { ast::def_ty(did) | ast::def_struct(did) => { ast_path_to_ty(self, rscope, did, path).ty } ast::def_prim_ty(nty) => { match nty { ast::ty_bool => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_bool(tcx) } ast::ty_int(it) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_mach_int(tcx, it) } ast::ty_uint(uit) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_mach_uint(tcx, uit) } ast::ty_float(ft) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_mach_float(tcx, ft) } ast::ty_str => { tcx.sess.span_err(ast_ty.span, ~"bare `str` is not a type"); // return /something/ so they can at least get more errors ty::mk_estr(tcx, ty::vstore_uniq) } } } ast::def_ty_param(id, n) => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); ty::mk_param(tcx, n, id) } ast::def_self_ty(id) => { // n.b.: resolve guarantees that the self type only appears in a // trait, which we rely upon in various places when creating // substs check_path_args(tcx, path, NO_TPS | NO_REGIONS); let did = ast_util::local_def(id); ty::mk_self(tcx, did) } _ => { tcx.sess.span_fatal(ast_ty.span, ~"found type name used as a variable"); } } } ast::ty_fixed_length_vec(ref a_mt, e) => { match const_eval::eval_const_expr_partial(tcx, e) { Ok(ref r) => { match *r { const_eval::const_int(i) => ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt), ty::vstore_fixed(i as uint)), const_eval::const_uint(i) => ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt), ty::vstore_fixed(i as uint)), _ => { tcx.sess.span_fatal( ast_ty.span, ~"expected constant expr for vector length"); } } } Err(ref r) => { tcx.sess.span_fatal( ast_ty.span, fmt!("expected constant expr for vector length: %s", *r)); } } } ast::ty_infer => { // ty_infer should only appear as the type of arguments or return // values in a fn_expr, or as the type of local variables. Both of // these cases are handled specially and should not descend into this // routine. self.tcx().sess.span_bug( ast_ty.span, ~"found `ty_infer` in unexpected place"); } ast::ty_mac(_) => { tcx.sess.span_bug(ast_ty.span, ~"found `ty_mac` in unexpected place"); } }; tcx.ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_resolved(typ)); return typ; } pub fn ty_of_arg<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, a: ast::arg, expected_ty: Option<ty::arg>) -> ty::arg { let ty = match a.ty.node { ast::ty_infer if expected_ty.is_some() => expected_ty.get().ty, ast::ty_infer => self.ty_infer(a.ty.span), _ => ast_ty_to_ty(self, rscope, a.ty) }; let mode = { match a.mode { ast::infer(_) if expected_ty.is_some() => { result::get(&ty::unify_mode( self.tcx(), ty::expected_found {expected: expected_ty.get().mode, found: a.mode})) } ast::infer(_) => { match ty::get(ty).sty { // If the type is not specified, then this must be a fn expr. // Leave the mode as infer(_), it will get inferred based // on constraints elsewhere. ty::ty_infer(_) => a.mode, // If the type is known, then use the default for that type. // Here we unify m and the default. This should update the // tables in tcx but should never fail, because nothing else // will have been unified with m yet: _ => { let m1 = ast::expl(ty::default_arg_mode_for_ty(self.tcx(), ty)); result::get(&ty::unify_mode( self.tcx(), ty::expected_found {expected: m1, found: a.mode})) } } } ast::expl(_) => a.mode } }; arg {mode: mode, ty: ty} } pub fn bound_lifetimes<AC:AstConv>( self: &AC, ast_lifetimes: &OptVec<ast::Lifetime>) -> OptVec<ast::ident> { /*! * * Converts a list of lifetimes into a list of bound identifier * names. Does not permit special names like 'static or 'self to * be bound. Note that this function is for use in closures, * methods, and fn definitions. It is legal to bind 'self in a * type. Eventually this distinction should go away and the same * rules should apply everywhere ('self would not be a special name * at that point). */ let special_idents = [special_idents::static, special_idents::self_]; let mut bound_lifetime_names = opt_vec::Empty; ast_lifetimes.map_to_vec(|ast_lifetime| { if special_idents.any(|&i| i == ast_lifetime.ident) { self.tcx().sess.span_err( ast_lifetime.span, fmt!("illegal lifetime parameter name: `%s`", lifetime_to_str(ast_lifetime, self.tcx().sess.intr()))); } else { bound_lifetime_names.push(ast_lifetime.ident); } }); bound_lifetime_names } pub fn ty_of_bare_fn<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, purity: ast::purity, abi: AbiSet, lifetimes: &OptVec<ast::Lifetime>, decl: &ast::fn_decl) -> ty::BareFnTy { debug!("ty_of_bare_fn"); // new region names that appear inside of the fn decl are bound to // that function type let bound_lifetime_names = bound_lifetimes(self, lifetimes); let rb = in_binding_rscope(rscope, RegionParamNames(copy bound_lifetime_names)); let input_tys = decl.inputs.map(|a| ty_of_arg(self, &rb, *a, None)); let output_ty = match decl.output.node { ast::ty_infer => self.ty_infer(decl.output.span), _ => ast_ty_to_ty(self, &rb, decl.output) }; ty::BareFnTy { purity: purity, abis: abi, sig: ty::FnSig {bound_lifetime_names: bound_lifetime_names, inputs: input_tys, output: output_ty} } } pub fn ty_of_closure<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, sigil: ast::Sigil, purity: ast::purity, onceness: ast::Onceness, opt_lifetime: Option<@ast::Lifetime>, decl: &ast::fn_decl, expected_sig: Option<ty::FnSig>, lifetimes: &OptVec<ast::Lifetime>, span: span) -> ty::ClosureTy { // The caller should not both provide explicit bound lifetime // names and expected types. Either we infer the bound lifetime // names or they are provided, but not both. assert!(lifetimes.is_empty() || expected_sig.is_none()); debug!("ty_of_fn_decl"); let _i = indenter(); // resolve the function bound region in the original region // scope `rscope`, not the scope of the function parameters let bound_region = match opt_lifetime { Some(_) => { ast_region_to_region(self, rscope, span, opt_lifetime) } None => { match sigil { ast::OwnedSigil | ast::ManagedSigil => { // @fn(), ~fn() default to static as the bound // on their upvars: ty::re_static } ast::BorrowedSigil => { // &fn() defaults as normal for an omitted lifetime: ast_region_to_region(self, rscope, span, opt_lifetime) } } } }; // new region names that appear inside of the fn decl are bound to // that function type let bound_lifetime_names = bound_lifetimes(self, lifetimes); let rb = in_binding_rscope(rscope, RegionParamNames(copy bound_lifetime_names)); let input_tys = do decl.inputs.mapi |i, a| { let expected_arg_ty = do expected_sig.chain_ref |e| { // no guarantee that the correct number of expected args // were supplied if i < e.inputs.len() {Some(e.inputs[i])} else {None} }; ty_of_arg(self, &rb, *a, expected_arg_ty) }; let expected_ret_ty = expected_sig.map(|e| e.output); let output_ty = match decl.output.node { ast::ty_infer if expected_ret_ty.is_some() => expected_ret_ty.get(), ast::ty_infer => self.ty_infer(decl.output.span), _ => ast_ty_to_ty(self, &rb, decl.output) }; ty::ClosureTy { purity: purity, sigil: sigil, onceness: onceness, region: bound_region, sig: ty::FnSig {bound_lifetime_names: bound_lifetime_names, inputs: input_tys, output: output_ty} } }
* Case (b) says that if you have a type: * type foo<'self> = ...; * type bar = fn(&foo, &a.foo) * The fully expanded version of type bar is: * type bar = fn(&'foo &, &a.foo<'a>)
random_line_split
static-assets-loader.ts
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {ConfigOptions} from "config/variables"; import webpack from "webpack"; export function getStaticAssetsLoader(configOptions: ConfigOptions): webpack.RuleSetRule
{ return { test: /\.(woff|woff2|ttf|eot|svg|png|gif|jpeg|jpg)(\?v=\d+\.\d+\.\d+)?$/, use: [ { loader: "file-loader", options: { name: configOptions.production ? "[name]-[hash].[ext]" : "[name].[ext]", outputPath: configOptions.production ? "media/" : "fonts/", esModule: false } } ] }; }
identifier_body
static-assets-loader.ts
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software
*/ import {ConfigOptions} from "config/variables"; import webpack from "webpack"; export function getStaticAssetsLoader(configOptions: ConfigOptions): webpack.RuleSetRule { return { test: /\.(woff|woff2|ttf|eot|svg|png|gif|jpeg|jpg)(\?v=\d+\.\d+\.\d+)?$/, use: [ { loader: "file-loader", options: { name: configOptions.production ? "[name]-[hash].[ext]" : "[name].[ext]", outputPath: configOptions.production ? "media/" : "fonts/", esModule: false } } ] }; }
* distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.
random_line_split
static-assets-loader.ts
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {ConfigOptions} from "config/variables"; import webpack from "webpack"; export function
(configOptions: ConfigOptions): webpack.RuleSetRule { return { test: /\.(woff|woff2|ttf|eot|svg|png|gif|jpeg|jpg)(\?v=\d+\.\d+\.\d+)?$/, use: [ { loader: "file-loader", options: { name: configOptions.production ? "[name]-[hash].[ext]" : "[name].[ext]", outputPath: configOptions.production ? "media/" : "fonts/", esModule: false } } ] }; }
getStaticAssetsLoader
identifier_name
reporter.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use crate::cpu::collector::{register_collector, Collector, CollectorHandle}; use crate::cpu::recorder::CpuRecords; use crate::Config; use std::fmt::{self, Display, Formatter}; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::SeqCst; use std::sync::Arc; use collections::HashMap; use futures::SinkExt; use grpcio::{CallOption, ChannelBuilder, Environment, WriteFlags}; use kvproto::resource_usage_agent::{CpuTimeRecord, ResourceUsageAgentClient}; use tikv_util::time::Duration; use tikv_util::worker::{Runnable, RunnableWithTimer, Scheduler}; pub struct CpuRecordsCollector { scheduler: Scheduler<Task>, } impl CpuRecordsCollector { pub fn
(scheduler: Scheduler<Task>) -> Self { Self { scheduler } } } impl Collector for CpuRecordsCollector { fn collect(&self, records: Arc<CpuRecords>) { self.scheduler.schedule(Task::CpuRecords(records)).ok(); } } pub enum Task { ConfigChange(Config), CpuRecords(Arc<CpuRecords>), } impl Display for Task { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Task::ConfigChange(_) => { write!(f, "ConfigChange")?; } Task::CpuRecords(_) => { write!(f, "CpuRecords")?; } } Ok(()) } } pub struct ResourceMeteringReporter { config: Config, env: Arc<Environment>, scheduler: Scheduler<Task>, // TODO: mock client for testing client: Option<ResourceUsageAgentClient>, reporting: Arc<AtomicBool>, cpu_records_collector: Option<CollectorHandle>, // resource_tag -> ([timestamp_secs], [cpu_time_ms], total_cpu_time_ms) records: HashMap<Vec<u8>, (Vec<u64>, Vec<u32>, u32)>, // timestamp_secs -> cpu_time_ms others: HashMap<u64, u32>, find_top_k: Vec<u32>, } impl ResourceMeteringReporter { pub fn new(config: Config, scheduler: Scheduler<Task>, env: Arc<Environment>) -> Self { let mut reporter = Self { config, env, scheduler, client: None, reporting: Arc::new(AtomicBool::new(false)), cpu_records_collector: None, records: HashMap::default(), others: HashMap::default(), find_top_k: Vec::default(), }; if reporter.config.should_report() { reporter.init_client(); } reporter } pub fn init_client(&mut self) { let channel = { let cb = ChannelBuilder::new(self.env.clone()) .keepalive_time(Duration::from_secs(10)) .keepalive_timeout(Duration::from_secs(3)); cb.connect(&self.config.agent_address) }; self.client = Some(ResourceUsageAgentClient::new(channel)); if self.cpu_records_collector.is_none() { self.cpu_records_collector = Some(register_collector(Box::new( CpuRecordsCollector::new(self.scheduler.clone()), ))); } } } impl Runnable for ResourceMeteringReporter { type Task = Task; fn run(&mut self, task: Self::Task) { match task { Task::ConfigChange(new_config) => { let old_config_enabled = self.config.enabled; let old_config_agent_address = self.config.agent_address.clone(); self.config = new_config; if !self.config.should_report() { self.client.take(); self.cpu_records_collector.take(); } else if self.config.agent_address != old_config_agent_address || self.config.enabled != old_config_enabled { self.init_client(); } } Task::CpuRecords(records) => { let timestamp_secs = records.begin_unix_time_secs; for (tag, ms) in &records.records { let tag = &tag.infos.extra_attachment; if tag.is_empty() { continue; } let ms = *ms as u32; match self.records.get_mut(tag) { Some((ts, cpu_time, total)) => { if *ts.last().unwrap() == timestamp_secs { *cpu_time.last_mut().unwrap() += ms; } else { ts.push(timestamp_secs); cpu_time.push(ms); } *total += ms; } None => { self.records .insert(tag.clone(), (vec![timestamp_secs], vec![ms], ms)); } } } if self.records.len() > self.config.max_resource_groups { self.find_top_k.clear(); for (_, _, total) in self.records.values() { self.find_top_k.push(*total); } pdqselect::select_by( &mut self.find_top_k, self.config.max_resource_groups, |a, b| b.cmp(a), ); let kth = self.find_top_k[self.config.max_resource_groups]; let others = &mut self.others; self.records .drain_filter(|_, (_, _, total)| *total <= kth) .for_each(|(_, (secs_list, cpu_time_list, _))| { secs_list .into_iter() .zip(cpu_time_list.into_iter()) .for_each(|(secs, cpu_time)| { *others.entry(secs).or_insert(0) += cpu_time }) }); } } } } fn shutdown(&mut self) { self.cpu_records_collector.take(); self.client.take(); } } impl RunnableWithTimer for ResourceMeteringReporter { fn on_timeout(&mut self) { if self.records.is_empty() { assert!(self.others.is_empty()); return; } let records = std::mem::take(&mut self.records); let others = std::mem::take(&mut self.others); if self.reporting.load(SeqCst) { return; } if let Some(client) = self.client.as_ref() { match client.report_cpu_time_opt(CallOption::default().timeout(Duration::from_secs(2))) { Ok((mut tx, rx)) => { self.reporting.store(true, SeqCst); let reporting = self.reporting.clone(); client.spawn(async move { defer!(reporting.store(false, SeqCst)); for (tag, (timestamp_list, cpu_time_ms_list, _)) in records { let mut req = CpuTimeRecord::default(); req.set_resource_group_tag(tag); req.set_record_list_timestamp_sec(timestamp_list); req.set_record_list_cpu_time_ms(cpu_time_ms_list); if tx.send((req, WriteFlags::default())).await.is_err() { return; } } // others if !others.is_empty() { let timestamp_list = others.keys().cloned().collect::<Vec<_>>(); let cpu_time_ms_list = others.values().cloned().collect::<Vec<_>>(); let mut req = CpuTimeRecord::default(); req.set_record_list_timestamp_sec(timestamp_list); req.set_record_list_cpu_time_ms(cpu_time_ms_list); if tx.send((req, WriteFlags::default())).await.is_err() { return; } } if tx.close().await.is_err() { return; } rx.await.ok(); }); } Err(err) => { warn!("failed to connect resource usage agent"; "error" => ?err); } } } } fn get_interval(&self) -> Duration { self.config.report_agent_interval.0 } }
new
identifier_name
reporter.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use crate::cpu::collector::{register_collector, Collector, CollectorHandle}; use crate::cpu::recorder::CpuRecords; use crate::Config; use std::fmt::{self, Display, Formatter}; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::SeqCst; use std::sync::Arc; use collections::HashMap; use futures::SinkExt; use grpcio::{CallOption, ChannelBuilder, Environment, WriteFlags}; use kvproto::resource_usage_agent::{CpuTimeRecord, ResourceUsageAgentClient}; use tikv_util::time::Duration; use tikv_util::worker::{Runnable, RunnableWithTimer, Scheduler}; pub struct CpuRecordsCollector { scheduler: Scheduler<Task>, } impl CpuRecordsCollector { pub fn new(scheduler: Scheduler<Task>) -> Self { Self { scheduler } } } impl Collector for CpuRecordsCollector { fn collect(&self, records: Arc<CpuRecords>) { self.scheduler.schedule(Task::CpuRecords(records)).ok(); } } pub enum Task { ConfigChange(Config), CpuRecords(Arc<CpuRecords>), } impl Display for Task { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Task::ConfigChange(_) => { write!(f, "ConfigChange")?; } Task::CpuRecords(_) => { write!(f, "CpuRecords")?; } } Ok(()) } } pub struct ResourceMeteringReporter { config: Config, env: Arc<Environment>, scheduler: Scheduler<Task>, // TODO: mock client for testing client: Option<ResourceUsageAgentClient>, reporting: Arc<AtomicBool>, cpu_records_collector: Option<CollectorHandle>, // resource_tag -> ([timestamp_secs], [cpu_time_ms], total_cpu_time_ms) records: HashMap<Vec<u8>, (Vec<u64>, Vec<u32>, u32)>, // timestamp_secs -> cpu_time_ms others: HashMap<u64, u32>, find_top_k: Vec<u32>, } impl ResourceMeteringReporter { pub fn new(config: Config, scheduler: Scheduler<Task>, env: Arc<Environment>) -> Self { let mut reporter = Self { config, env, scheduler, client: None, reporting: Arc::new(AtomicBool::new(false)), cpu_records_collector: None, records: HashMap::default(), others: HashMap::default(), find_top_k: Vec::default(), }; if reporter.config.should_report() { reporter.init_client(); } reporter } pub fn init_client(&mut self)
} impl Runnable for ResourceMeteringReporter { type Task = Task; fn run(&mut self, task: Self::Task) { match task { Task::ConfigChange(new_config) => { let old_config_enabled = self.config.enabled; let old_config_agent_address = self.config.agent_address.clone(); self.config = new_config; if !self.config.should_report() { self.client.take(); self.cpu_records_collector.take(); } else if self.config.agent_address != old_config_agent_address || self.config.enabled != old_config_enabled { self.init_client(); } } Task::CpuRecords(records) => { let timestamp_secs = records.begin_unix_time_secs; for (tag, ms) in &records.records { let tag = &tag.infos.extra_attachment; if tag.is_empty() { continue; } let ms = *ms as u32; match self.records.get_mut(tag) { Some((ts, cpu_time, total)) => { if *ts.last().unwrap() == timestamp_secs { *cpu_time.last_mut().unwrap() += ms; } else { ts.push(timestamp_secs); cpu_time.push(ms); } *total += ms; } None => { self.records .insert(tag.clone(), (vec![timestamp_secs], vec![ms], ms)); } } } if self.records.len() > self.config.max_resource_groups { self.find_top_k.clear(); for (_, _, total) in self.records.values() { self.find_top_k.push(*total); } pdqselect::select_by( &mut self.find_top_k, self.config.max_resource_groups, |a, b| b.cmp(a), ); let kth = self.find_top_k[self.config.max_resource_groups]; let others = &mut self.others; self.records .drain_filter(|_, (_, _, total)| *total <= kth) .for_each(|(_, (secs_list, cpu_time_list, _))| { secs_list .into_iter() .zip(cpu_time_list.into_iter()) .for_each(|(secs, cpu_time)| { *others.entry(secs).or_insert(0) += cpu_time }) }); } } } } fn shutdown(&mut self) { self.cpu_records_collector.take(); self.client.take(); } } impl RunnableWithTimer for ResourceMeteringReporter { fn on_timeout(&mut self) { if self.records.is_empty() { assert!(self.others.is_empty()); return; } let records = std::mem::take(&mut self.records); let others = std::mem::take(&mut self.others); if self.reporting.load(SeqCst) { return; } if let Some(client) = self.client.as_ref() { match client.report_cpu_time_opt(CallOption::default().timeout(Duration::from_secs(2))) { Ok((mut tx, rx)) => { self.reporting.store(true, SeqCst); let reporting = self.reporting.clone(); client.spawn(async move { defer!(reporting.store(false, SeqCst)); for (tag, (timestamp_list, cpu_time_ms_list, _)) in records { let mut req = CpuTimeRecord::default(); req.set_resource_group_tag(tag); req.set_record_list_timestamp_sec(timestamp_list); req.set_record_list_cpu_time_ms(cpu_time_ms_list); if tx.send((req, WriteFlags::default())).await.is_err() { return; } } // others if !others.is_empty() { let timestamp_list = others.keys().cloned().collect::<Vec<_>>(); let cpu_time_ms_list = others.values().cloned().collect::<Vec<_>>(); let mut req = CpuTimeRecord::default(); req.set_record_list_timestamp_sec(timestamp_list); req.set_record_list_cpu_time_ms(cpu_time_ms_list); if tx.send((req, WriteFlags::default())).await.is_err() { return; } } if tx.close().await.is_err() { return; } rx.await.ok(); }); } Err(err) => { warn!("failed to connect resource usage agent"; "error" => ?err); } } } } fn get_interval(&self) -> Duration { self.config.report_agent_interval.0 } }
{ let channel = { let cb = ChannelBuilder::new(self.env.clone()) .keepalive_time(Duration::from_secs(10)) .keepalive_timeout(Duration::from_secs(3)); cb.connect(&self.config.agent_address) }; self.client = Some(ResourceUsageAgentClient::new(channel)); if self.cpu_records_collector.is_none() { self.cpu_records_collector = Some(register_collector(Box::new( CpuRecordsCollector::new(self.scheduler.clone()), ))); } }
identifier_body
reporter.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use crate::cpu::collector::{register_collector, Collector, CollectorHandle}; use crate::cpu::recorder::CpuRecords; use crate::Config; use std::fmt::{self, Display, Formatter}; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::SeqCst; use std::sync::Arc; use collections::HashMap; use futures::SinkExt; use grpcio::{CallOption, ChannelBuilder, Environment, WriteFlags}; use kvproto::resource_usage_agent::{CpuTimeRecord, ResourceUsageAgentClient}; use tikv_util::time::Duration; use tikv_util::worker::{Runnable, RunnableWithTimer, Scheduler}; pub struct CpuRecordsCollector { scheduler: Scheduler<Task>, } impl CpuRecordsCollector { pub fn new(scheduler: Scheduler<Task>) -> Self { Self { scheduler } } } impl Collector for CpuRecordsCollector { fn collect(&self, records: Arc<CpuRecords>) { self.scheduler.schedule(Task::CpuRecords(records)).ok(); } } pub enum Task { ConfigChange(Config), CpuRecords(Arc<CpuRecords>), } impl Display for Task { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Task::ConfigChange(_) => { write!(f, "ConfigChange")?; } Task::CpuRecords(_) => { write!(f, "CpuRecords")?; } } Ok(()) } } pub struct ResourceMeteringReporter { config: Config, env: Arc<Environment>, scheduler: Scheduler<Task>, // TODO: mock client for testing client: Option<ResourceUsageAgentClient>, reporting: Arc<AtomicBool>, cpu_records_collector: Option<CollectorHandle>, // resource_tag -> ([timestamp_secs], [cpu_time_ms], total_cpu_time_ms) records: HashMap<Vec<u8>, (Vec<u64>, Vec<u32>, u32)>, // timestamp_secs -> cpu_time_ms others: HashMap<u64, u32>, find_top_k: Vec<u32>, } impl ResourceMeteringReporter { pub fn new(config: Config, scheduler: Scheduler<Task>, env: Arc<Environment>) -> Self { let mut reporter = Self { config, env, scheduler, client: None, reporting: Arc::new(AtomicBool::new(false)), cpu_records_collector: None, records: HashMap::default(), others: HashMap::default(), find_top_k: Vec::default(), }; if reporter.config.should_report() { reporter.init_client(); } reporter } pub fn init_client(&mut self) { let channel = { let cb = ChannelBuilder::new(self.env.clone()) .keepalive_time(Duration::from_secs(10)) .keepalive_timeout(Duration::from_secs(3)); cb.connect(&self.config.agent_address) }; self.client = Some(ResourceUsageAgentClient::new(channel)); if self.cpu_records_collector.is_none() { self.cpu_records_collector = Some(register_collector(Box::new( CpuRecordsCollector::new(self.scheduler.clone()), ))); } } } impl Runnable for ResourceMeteringReporter { type Task = Task; fn run(&mut self, task: Self::Task) { match task { Task::ConfigChange(new_config) => { let old_config_enabled = self.config.enabled; let old_config_agent_address = self.config.agent_address.clone(); self.config = new_config; if !self.config.should_report() { self.client.take(); self.cpu_records_collector.take(); } else if self.config.agent_address != old_config_agent_address || self.config.enabled != old_config_enabled { self.init_client(); } } Task::CpuRecords(records) => { let timestamp_secs = records.begin_unix_time_secs; for (tag, ms) in &records.records { let tag = &tag.infos.extra_attachment; if tag.is_empty() { continue; } let ms = *ms as u32; match self.records.get_mut(tag) { Some((ts, cpu_time, total)) => { if *ts.last().unwrap() == timestamp_secs { *cpu_time.last_mut().unwrap() += ms; } else { ts.push(timestamp_secs); cpu_time.push(ms); } *total += ms; } None => { self.records .insert(tag.clone(), (vec![timestamp_secs], vec![ms], ms)); } } } if self.records.len() > self.config.max_resource_groups { self.find_top_k.clear(); for (_, _, total) in self.records.values() { self.find_top_k.push(*total); } pdqselect::select_by( &mut self.find_top_k, self.config.max_resource_groups, |a, b| b.cmp(a), ); let kth = self.find_top_k[self.config.max_resource_groups]; let others = &mut self.others; self.records .drain_filter(|_, (_, _, total)| *total <= kth) .for_each(|(_, (secs_list, cpu_time_list, _))| { secs_list .into_iter() .zip(cpu_time_list.into_iter()) .for_each(|(secs, cpu_time)| { *others.entry(secs).or_insert(0) += cpu_time }) }); } } } } fn shutdown(&mut self) { self.cpu_records_collector.take(); self.client.take(); } } impl RunnableWithTimer for ResourceMeteringReporter { fn on_timeout(&mut self) { if self.records.is_empty() { assert!(self.others.is_empty()); return; } let records = std::mem::take(&mut self.records); let others = std::mem::take(&mut self.others); if self.reporting.load(SeqCst) { return; } if let Some(client) = self.client.as_ref() { match client.report_cpu_time_opt(CallOption::default().timeout(Duration::from_secs(2))) { Ok((mut tx, rx)) => { self.reporting.store(true, SeqCst); let reporting = self.reporting.clone(); client.spawn(async move { defer!(reporting.store(false, SeqCst));
req.set_record_list_timestamp_sec(timestamp_list); req.set_record_list_cpu_time_ms(cpu_time_ms_list); if tx.send((req, WriteFlags::default())).await.is_err() { return; } } // others if !others.is_empty() { let timestamp_list = others.keys().cloned().collect::<Vec<_>>(); let cpu_time_ms_list = others.values().cloned().collect::<Vec<_>>(); let mut req = CpuTimeRecord::default(); req.set_record_list_timestamp_sec(timestamp_list); req.set_record_list_cpu_time_ms(cpu_time_ms_list); if tx.send((req, WriteFlags::default())).await.is_err() { return; } } if tx.close().await.is_err() { return; } rx.await.ok(); }); } Err(err) => { warn!("failed to connect resource usage agent"; "error" => ?err); } } } } fn get_interval(&self) -> Duration { self.config.report_agent_interval.0 } }
for (tag, (timestamp_list, cpu_time_ms_list, _)) in records { let mut req = CpuTimeRecord::default(); req.set_resource_group_tag(tag);
random_line_split
mod.rs
// This file is released under the same terms as Rust itself. pub mod github_status; pub mod jenkins; use config::PipelinesConfig; use hyper::Url; use pipeline::{GetPipelineId, PipelineId}; use vcs::Commit; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct CiId(pub i32); #[derive(Clone, Debug)] pub enum Message { StartBuild(CiId, Commit), } #[derive(Clone, Debug)] pub enum
{ BuildStarted(CiId, Commit, Option<Url>), BuildSucceeded(CiId, Commit, Option<Url>), BuildFailed(CiId, Commit, Option<Url>), } impl GetPipelineId for Event { fn pipeline_id<C: PipelinesConfig + ?Sized>(&self, config: &C) -> PipelineId { let ci_id = match *self { Event::BuildStarted(i, _, _) => i, Event::BuildSucceeded(i, _, _) => i, Event::BuildFailed(i, _, _) => i, }; config.by_ci_id(ci_id).pipeline_id } }
Event
identifier_name
mod.rs
// This file is released under the same terms as Rust itself. pub mod github_status; pub mod jenkins; use config::PipelinesConfig; use hyper::Url; use pipeline::{GetPipelineId, PipelineId}; use vcs::Commit; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct CiId(pub i32); #[derive(Clone, Debug)] pub enum Message { StartBuild(CiId, Commit), } #[derive(Clone, Debug)] pub enum Event { BuildStarted(CiId, Commit, Option<Url>),
impl GetPipelineId for Event { fn pipeline_id<C: PipelinesConfig + ?Sized>(&self, config: &C) -> PipelineId { let ci_id = match *self { Event::BuildStarted(i, _, _) => i, Event::BuildSucceeded(i, _, _) => i, Event::BuildFailed(i, _, _) => i, }; config.by_ci_id(ci_id).pipeline_id } }
BuildSucceeded(CiId, Commit, Option<Url>), BuildFailed(CiId, Commit, Option<Url>), }
random_line_split
arm.rs
//! Contains arm-specific types use core::convert::From; use core::{cmp, fmt, slice}; use capstone_sys::{ arm_op_mem, arm_op_type, cs_arm, cs_arm_op, arm_shifter, cs_arm_op__bindgen_ty_2}; use libc::c_uint; pub use crate::arch::arch_builder::arm::*; use crate::arch::DetailsArchInsn; use crate::instruction::{RegId, RegIdInt}; pub use capstone_sys::arm_insn_group as ArmInsnGroup; pub use capstone_sys::arm_insn as ArmInsn; pub use capstone_sys::arm_reg as ArmReg; pub use capstone_sys::arm_vectordata_type as ArmVectorData; pub use capstone_sys::arm_cpsmode_type as ArmCPSMode; pub use capstone_sys::arm_cpsflag_type as ArmCPSFlag; pub use capstone_sys::arm_cc as ArmCC; pub use capstone_sys::arm_mem_barrier as ArmMemBarrier; pub use capstone_sys::arm_setend_type as ArmSetendType; /// Contains ARM-specific details for an instruction pub struct ArmInsnDetail<'a>(pub(crate) &'a cs_arm); /// ARM shift amount #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] pub enum ArmShift { Invalid, /// Arithmetic shift right (immediate) Asr(u32), /// Logical shift lift (immediate) Lsl(u32), /// Logical shift right (immediate) Lsr(u32), /// Rotate right (immediate) Ror(u32), /// Rotate right with extend (immediate) Rrx(u32), /// Arithmetic shift right (register) AsrReg(RegId), /// Logical shift lift (register) LslReg(RegId), /// Logical shift right (register) LsrReg(RegId), /// Rotate right (register) RorReg(RegId), /// Rotate right with extend (register) RrxReg(RegId), } impl ArmShift { fn new(type_: arm_shifter, value: c_uint) -> ArmShift { use self::arm_shifter::*; use self::ArmShift::*; macro_rules! arm_shift_match { ( imm = [ $( $imm_r_enum:ident = $imm_c_enum:ident, )* ] reg = [ $( $reg_r_enum:ident = $reg_c_enum:ident, )* ] ) => { match type_ { ARM_SFT_INVALID => Invalid, $( $imm_c_enum => $imm_r_enum(value as u32) , )* $( $reg_c_enum => $reg_r_enum(RegId(value as RegIdInt)) , )* } } } arm_shift_match!( imm = [ Asr = ARM_SFT_ASR, Lsl = ARM_SFT_LSL, Lsr = ARM_SFT_LSR, Ror = ARM_SFT_ROR, Rrx = ARM_SFT_RRX, ] reg = [ AsrReg = ARM_SFT_ASR_REG, LslReg = ARM_SFT_LSL_REG, LsrReg = ARM_SFT_LSR_REG, RorReg = ARM_SFT_ROR_REG, RrxReg = ARM_SFT_RRX_REG, ] ) } } impl ArmOperandType { fn new(op_type: arm_op_type, value: cs_arm_op__bindgen_ty_2) -> ArmOperandType { use self::arm_op_type::*; use self::ArmOperandType::*; match op_type { ARM_OP_INVALID => Invalid, ARM_OP_REG => Reg(RegId(unsafe { value.reg } as RegIdInt)), ARM_OP_IMM => Imm(unsafe { value.imm }), ARM_OP_MEM => Mem(ArmOpMem(unsafe { value.mem })), ARM_OP_FP => Fp(unsafe { value.fp }), ARM_OP_CIMM => Cimm(unsafe { value.imm }), ARM_OP_PIMM => Pimm(unsafe { value.imm }), ARM_OP_SETEND => Setend(unsafe { value.setend }), ARM_OP_SYSREG => SysReg(RegId(unsafe { value.reg } as RegIdInt)), } } } /// ARM operand #[derive(Clone, Debug, PartialEq)] pub struct ArmOperand { /// Vector Index for some vector operands pub vector_index: Option<u32>, /// Whether operand is subtracted pub subtracted: bool, pub shift: ArmShift, /// Operand type pub op_type: ArmOperandType, } /// ARM operand #[derive(Clone, Debug, PartialEq)] pub enum ArmOperandType { /// Register Reg(RegId), /// Immediate Imm(i32), /// Memory Mem(ArmOpMem), /// Floating point Fp(f64), /// C-IMM Cimm(i32), /// P-IMM Pimm(i32), /// SETEND instruction endianness Setend(ArmSetendType), /// Sysreg SysReg(RegId), /// Invalid Invalid, } /// ARM memory operand #[derive(Debug, Copy, Clone)] pub struct ArmOpMem(pub(crate) arm_op_mem); impl<'a> ArmInsnDetail<'a> { /// Whether the instruction is a user mode pub fn usermode(&self) -> bool
/// Vector size pub fn vector_size(&self) -> i32 { self.0.vector_size as i32 } /// Type of vector data pub fn vector_data(&self) -> ArmVectorData { self.0.vector_data } /// CPS mode for CPS instruction pub fn cps_mode(&self) -> ArmCPSMode { self.0.cps_mode } /// CPS flag for CPS instruction pub fn cps_flag(&self) -> ArmCPSFlag { self.0.cps_flag } /// Condition codes pub fn cc(&self) -> ArmCC { self.0.cc } /// Whether this insn updates flags pub fn update_flags(&self) -> bool { self.0.update_flags } /// Whether writeback is required pub fn writeback(&self) -> bool { self.0.writeback } /// Memory barrier pub fn mem_barrier(&self) -> ArmMemBarrier { self.0.mem_barrier } } impl_PartialEq_repr_fields!(ArmInsnDetail<'a> [ 'a ]; usermode, vector_size, vector_data, cps_mode, cps_flag, cc, update_flags, writeback, mem_barrier, operands ); impl ArmOpMem { /// Base register pub fn base(&self) -> RegId { RegId(self.0.base as RegIdInt) } /// Index value pub fn index(&self) -> RegId { RegId(self.0.index as RegIdInt) } /// Scale for index register (can be 1, or -1) pub fn scale(&self) -> i32 { self.0.scale as i32 } /// Disp value pub fn disp(&self) -> i32 { self.0.disp as i32 } } impl_PartialEq_repr_fields!(ArmOpMem; base, index, scale, disp ); impl cmp::Eq for ArmOpMem {} impl Default for ArmOperand { fn default() -> Self { ArmOperand { vector_index: None, subtracted: false, shift: ArmShift::Invalid, op_type: ArmOperandType::Invalid } } } impl<'a> From<&'a cs_arm_op> for ArmOperand { fn from(op: &cs_arm_op) -> ArmOperand { let shift = ArmShift::new(op.shift.type_, op.shift.value); let op_type = ArmOperandType::new(op.type_, op.__bindgen_anon_1); let vector_index = if op.vector_index >= 0 { Some(op.vector_index as u32) } else { None }; ArmOperand { vector_index, shift, op_type, subtracted: op.subtracted, } } } def_arch_details_struct!( InsnDetail = ArmInsnDetail; Operand = ArmOperand; OperandIterator = ArmOperandIterator; OperandIteratorLife = ArmOperandIterator<'a>; [ pub struct ArmOperandIterator<'a>(slice::Iter<'a, cs_arm_op>); ] cs_arch_op = cs_arm_op; cs_arch = cs_arm; ); #[cfg(test)] mod test { use super::*; use capstone_sys::*; #[test] fn test_armshift() { use super::arm_shifter::*; use super::ArmShift::*; use libc::c_uint; fn t(shift_type_value: (arm_shifter, c_uint), arm_shift: ArmShift) { let (shift_type, value) = shift_type_value; assert_eq!(arm_shift, ArmShift::new(shift_type, value)); } t((ARM_SFT_INVALID, 0), Invalid); t((ARM_SFT_ASR, 0), Asr(0)); t((ARM_SFT_ASR_REG, 42), AsrReg(RegId(42))); t((ARM_SFT_RRX_REG, 42), RrxReg(RegId(42))); } #[test] fn test_arm_op_type() { use super::arm_op_type::*; use super::ArmOperandType::*; fn t( op_type_value: (arm_op_type, cs_arm_op__bindgen_ty_2), expected_op_type: ArmOperandType, ) { let (op_type, op_value) = op_type_value; let op_type = ArmOperandType::new(op_type, op_value); assert_eq!(expected_op_type, op_type); } t( (ARM_OP_INVALID, cs_arm_op__bindgen_ty_2 { reg: 0 }), Invalid, ); t( (ARM_OP_REG, cs_arm_op__bindgen_ty_2 { reg: 0 }), Reg(RegId(0)), ); } #[test] fn test_arm_insn_detail_eq() { let a1 = cs_arm { usermode: false, vector_size: 0, vector_data: arm_vectordata_type::ARM_VECTORDATA_INVALID, cps_mode: arm_cpsmode_type::ARM_CPSMODE_INVALID, cps_flag: arm_cpsflag_type::ARM_CPSFLAG_INVALID, cc: arm_cc::ARM_CC_INVALID, update_flags: false, writeback: false, mem_barrier: arm_mem_barrier::ARM_MB_INVALID, op_count: 0, operands: [ cs_arm_op { vector_index: 0, shift: cs_arm_op__bindgen_ty_1 { type_: arm_shifter::ARM_SFT_INVALID, value: 0 }, type_: arm_op_type::ARM_OP_INVALID, __bindgen_anon_1: cs_arm_op__bindgen_ty_2 { imm: 0 }, subtracted: false, access: 0, neon_lane: 0, } ; 36] }; let a2 = cs_arm { usermode: true, ..a1 }; let a3 = cs_arm { op_count: 20, ..a1 }; let a4 = cs_arm { op_count: 19, ..a1 }; let a4_clone = a4.clone(); assert_eq!(ArmInsnDetail(&a1), ArmInsnDetail(&a1)); assert_ne!(ArmInsnDetail(&a1), ArmInsnDetail(&a2)); assert_ne!(ArmInsnDetail(&a1), ArmInsnDetail(&a3)); assert_ne!(ArmInsnDetail(&a3), ArmInsnDetail(&a4)); assert_eq!(ArmInsnDetail(&a4), ArmInsnDetail(&a4_clone)); } }
{ self.0.usermode }
identifier_body
arm.rs
//! Contains arm-specific types use core::convert::From; use core::{cmp, fmt, slice}; use capstone_sys::{ arm_op_mem, arm_op_type, cs_arm, cs_arm_op, arm_shifter, cs_arm_op__bindgen_ty_2};
use libc::c_uint; pub use crate::arch::arch_builder::arm::*; use crate::arch::DetailsArchInsn; use crate::instruction::{RegId, RegIdInt}; pub use capstone_sys::arm_insn_group as ArmInsnGroup; pub use capstone_sys::arm_insn as ArmInsn; pub use capstone_sys::arm_reg as ArmReg; pub use capstone_sys::arm_vectordata_type as ArmVectorData; pub use capstone_sys::arm_cpsmode_type as ArmCPSMode; pub use capstone_sys::arm_cpsflag_type as ArmCPSFlag; pub use capstone_sys::arm_cc as ArmCC; pub use capstone_sys::arm_mem_barrier as ArmMemBarrier; pub use capstone_sys::arm_setend_type as ArmSetendType; /// Contains ARM-specific details for an instruction pub struct ArmInsnDetail<'a>(pub(crate) &'a cs_arm); /// ARM shift amount #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] pub enum ArmShift { Invalid, /// Arithmetic shift right (immediate) Asr(u32), /// Logical shift lift (immediate) Lsl(u32), /// Logical shift right (immediate) Lsr(u32), /// Rotate right (immediate) Ror(u32), /// Rotate right with extend (immediate) Rrx(u32), /// Arithmetic shift right (register) AsrReg(RegId), /// Logical shift lift (register) LslReg(RegId), /// Logical shift right (register) LsrReg(RegId), /// Rotate right (register) RorReg(RegId), /// Rotate right with extend (register) RrxReg(RegId), } impl ArmShift { fn new(type_: arm_shifter, value: c_uint) -> ArmShift { use self::arm_shifter::*; use self::ArmShift::*; macro_rules! arm_shift_match { ( imm = [ $( $imm_r_enum:ident = $imm_c_enum:ident, )* ] reg = [ $( $reg_r_enum:ident = $reg_c_enum:ident, )* ] ) => { match type_ { ARM_SFT_INVALID => Invalid, $( $imm_c_enum => $imm_r_enum(value as u32) , )* $( $reg_c_enum => $reg_r_enum(RegId(value as RegIdInt)) , )* } } } arm_shift_match!( imm = [ Asr = ARM_SFT_ASR, Lsl = ARM_SFT_LSL, Lsr = ARM_SFT_LSR, Ror = ARM_SFT_ROR, Rrx = ARM_SFT_RRX, ] reg = [ AsrReg = ARM_SFT_ASR_REG, LslReg = ARM_SFT_LSL_REG, LsrReg = ARM_SFT_LSR_REG, RorReg = ARM_SFT_ROR_REG, RrxReg = ARM_SFT_RRX_REG, ] ) } } impl ArmOperandType { fn new(op_type: arm_op_type, value: cs_arm_op__bindgen_ty_2) -> ArmOperandType { use self::arm_op_type::*; use self::ArmOperandType::*; match op_type { ARM_OP_INVALID => Invalid, ARM_OP_REG => Reg(RegId(unsafe { value.reg } as RegIdInt)), ARM_OP_IMM => Imm(unsafe { value.imm }), ARM_OP_MEM => Mem(ArmOpMem(unsafe { value.mem })), ARM_OP_FP => Fp(unsafe { value.fp }), ARM_OP_CIMM => Cimm(unsafe { value.imm }), ARM_OP_PIMM => Pimm(unsafe { value.imm }), ARM_OP_SETEND => Setend(unsafe { value.setend }), ARM_OP_SYSREG => SysReg(RegId(unsafe { value.reg } as RegIdInt)), } } } /// ARM operand #[derive(Clone, Debug, PartialEq)] pub struct ArmOperand { /// Vector Index for some vector operands pub vector_index: Option<u32>, /// Whether operand is subtracted pub subtracted: bool, pub shift: ArmShift, /// Operand type pub op_type: ArmOperandType, } /// ARM operand #[derive(Clone, Debug, PartialEq)] pub enum ArmOperandType { /// Register Reg(RegId), /// Immediate Imm(i32), /// Memory Mem(ArmOpMem), /// Floating point Fp(f64), /// C-IMM Cimm(i32), /// P-IMM Pimm(i32), /// SETEND instruction endianness Setend(ArmSetendType), /// Sysreg SysReg(RegId), /// Invalid Invalid, } /// ARM memory operand #[derive(Debug, Copy, Clone)] pub struct ArmOpMem(pub(crate) arm_op_mem); impl<'a> ArmInsnDetail<'a> { /// Whether the instruction is a user mode pub fn usermode(&self) -> bool { self.0.usermode } /// Vector size pub fn vector_size(&self) -> i32 { self.0.vector_size as i32 } /// Type of vector data pub fn vector_data(&self) -> ArmVectorData { self.0.vector_data } /// CPS mode for CPS instruction pub fn cps_mode(&self) -> ArmCPSMode { self.0.cps_mode } /// CPS flag for CPS instruction pub fn cps_flag(&self) -> ArmCPSFlag { self.0.cps_flag } /// Condition codes pub fn cc(&self) -> ArmCC { self.0.cc } /// Whether this insn updates flags pub fn update_flags(&self) -> bool { self.0.update_flags } /// Whether writeback is required pub fn writeback(&self) -> bool { self.0.writeback } /// Memory barrier pub fn mem_barrier(&self) -> ArmMemBarrier { self.0.mem_barrier } } impl_PartialEq_repr_fields!(ArmInsnDetail<'a> [ 'a ]; usermode, vector_size, vector_data, cps_mode, cps_flag, cc, update_flags, writeback, mem_barrier, operands ); impl ArmOpMem { /// Base register pub fn base(&self) -> RegId { RegId(self.0.base as RegIdInt) } /// Index value pub fn index(&self) -> RegId { RegId(self.0.index as RegIdInt) } /// Scale for index register (can be 1, or -1) pub fn scale(&self) -> i32 { self.0.scale as i32 } /// Disp value pub fn disp(&self) -> i32 { self.0.disp as i32 } } impl_PartialEq_repr_fields!(ArmOpMem; base, index, scale, disp ); impl cmp::Eq for ArmOpMem {} impl Default for ArmOperand { fn default() -> Self { ArmOperand { vector_index: None, subtracted: false, shift: ArmShift::Invalid, op_type: ArmOperandType::Invalid } } } impl<'a> From<&'a cs_arm_op> for ArmOperand { fn from(op: &cs_arm_op) -> ArmOperand { let shift = ArmShift::new(op.shift.type_, op.shift.value); let op_type = ArmOperandType::new(op.type_, op.__bindgen_anon_1); let vector_index = if op.vector_index >= 0 { Some(op.vector_index as u32) } else { None }; ArmOperand { vector_index, shift, op_type, subtracted: op.subtracted, } } } def_arch_details_struct!( InsnDetail = ArmInsnDetail; Operand = ArmOperand; OperandIterator = ArmOperandIterator; OperandIteratorLife = ArmOperandIterator<'a>; [ pub struct ArmOperandIterator<'a>(slice::Iter<'a, cs_arm_op>); ] cs_arch_op = cs_arm_op; cs_arch = cs_arm; ); #[cfg(test)] mod test { use super::*; use capstone_sys::*; #[test] fn test_armshift() { use super::arm_shifter::*; use super::ArmShift::*; use libc::c_uint; fn t(shift_type_value: (arm_shifter, c_uint), arm_shift: ArmShift) { let (shift_type, value) = shift_type_value; assert_eq!(arm_shift, ArmShift::new(shift_type, value)); } t((ARM_SFT_INVALID, 0), Invalid); t((ARM_SFT_ASR, 0), Asr(0)); t((ARM_SFT_ASR_REG, 42), AsrReg(RegId(42))); t((ARM_SFT_RRX_REG, 42), RrxReg(RegId(42))); } #[test] fn test_arm_op_type() { use super::arm_op_type::*; use super::ArmOperandType::*; fn t( op_type_value: (arm_op_type, cs_arm_op__bindgen_ty_2), expected_op_type: ArmOperandType, ) { let (op_type, op_value) = op_type_value; let op_type = ArmOperandType::new(op_type, op_value); assert_eq!(expected_op_type, op_type); } t( (ARM_OP_INVALID, cs_arm_op__bindgen_ty_2 { reg: 0 }), Invalid, ); t( (ARM_OP_REG, cs_arm_op__bindgen_ty_2 { reg: 0 }), Reg(RegId(0)), ); } #[test] fn test_arm_insn_detail_eq() { let a1 = cs_arm { usermode: false, vector_size: 0, vector_data: arm_vectordata_type::ARM_VECTORDATA_INVALID, cps_mode: arm_cpsmode_type::ARM_CPSMODE_INVALID, cps_flag: arm_cpsflag_type::ARM_CPSFLAG_INVALID, cc: arm_cc::ARM_CC_INVALID, update_flags: false, writeback: false, mem_barrier: arm_mem_barrier::ARM_MB_INVALID, op_count: 0, operands: [ cs_arm_op { vector_index: 0, shift: cs_arm_op__bindgen_ty_1 { type_: arm_shifter::ARM_SFT_INVALID, value: 0 }, type_: arm_op_type::ARM_OP_INVALID, __bindgen_anon_1: cs_arm_op__bindgen_ty_2 { imm: 0 }, subtracted: false, access: 0, neon_lane: 0, } ; 36] }; let a2 = cs_arm { usermode: true, ..a1 }; let a3 = cs_arm { op_count: 20, ..a1 }; let a4 = cs_arm { op_count: 19, ..a1 }; let a4_clone = a4.clone(); assert_eq!(ArmInsnDetail(&a1), ArmInsnDetail(&a1)); assert_ne!(ArmInsnDetail(&a1), ArmInsnDetail(&a2)); assert_ne!(ArmInsnDetail(&a1), ArmInsnDetail(&a3)); assert_ne!(ArmInsnDetail(&a3), ArmInsnDetail(&a4)); assert_eq!(ArmInsnDetail(&a4), ArmInsnDetail(&a4_clone)); } }
random_line_split
arm.rs
//! Contains arm-specific types use core::convert::From; use core::{cmp, fmt, slice}; use capstone_sys::{ arm_op_mem, arm_op_type, cs_arm, cs_arm_op, arm_shifter, cs_arm_op__bindgen_ty_2}; use libc::c_uint; pub use crate::arch::arch_builder::arm::*; use crate::arch::DetailsArchInsn; use crate::instruction::{RegId, RegIdInt}; pub use capstone_sys::arm_insn_group as ArmInsnGroup; pub use capstone_sys::arm_insn as ArmInsn; pub use capstone_sys::arm_reg as ArmReg; pub use capstone_sys::arm_vectordata_type as ArmVectorData; pub use capstone_sys::arm_cpsmode_type as ArmCPSMode; pub use capstone_sys::arm_cpsflag_type as ArmCPSFlag; pub use capstone_sys::arm_cc as ArmCC; pub use capstone_sys::arm_mem_barrier as ArmMemBarrier; pub use capstone_sys::arm_setend_type as ArmSetendType; /// Contains ARM-specific details for an instruction pub struct ArmInsnDetail<'a>(pub(crate) &'a cs_arm); /// ARM shift amount #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] pub enum ArmShift { Invalid, /// Arithmetic shift right (immediate) Asr(u32), /// Logical shift lift (immediate) Lsl(u32), /// Logical shift right (immediate) Lsr(u32), /// Rotate right (immediate) Ror(u32), /// Rotate right with extend (immediate) Rrx(u32), /// Arithmetic shift right (register) AsrReg(RegId), /// Logical shift lift (register) LslReg(RegId), /// Logical shift right (register) LsrReg(RegId), /// Rotate right (register) RorReg(RegId), /// Rotate right with extend (register) RrxReg(RegId), } impl ArmShift { fn new(type_: arm_shifter, value: c_uint) -> ArmShift { use self::arm_shifter::*; use self::ArmShift::*; macro_rules! arm_shift_match { ( imm = [ $( $imm_r_enum:ident = $imm_c_enum:ident, )* ] reg = [ $( $reg_r_enum:ident = $reg_c_enum:ident, )* ] ) => { match type_ { ARM_SFT_INVALID => Invalid, $( $imm_c_enum => $imm_r_enum(value as u32) , )* $( $reg_c_enum => $reg_r_enum(RegId(value as RegIdInt)) , )* } } } arm_shift_match!( imm = [ Asr = ARM_SFT_ASR, Lsl = ARM_SFT_LSL, Lsr = ARM_SFT_LSR, Ror = ARM_SFT_ROR, Rrx = ARM_SFT_RRX, ] reg = [ AsrReg = ARM_SFT_ASR_REG, LslReg = ARM_SFT_LSL_REG, LsrReg = ARM_SFT_LSR_REG, RorReg = ARM_SFT_ROR_REG, RrxReg = ARM_SFT_RRX_REG, ] ) } } impl ArmOperandType { fn new(op_type: arm_op_type, value: cs_arm_op__bindgen_ty_2) -> ArmOperandType { use self::arm_op_type::*; use self::ArmOperandType::*; match op_type { ARM_OP_INVALID => Invalid, ARM_OP_REG => Reg(RegId(unsafe { value.reg } as RegIdInt)), ARM_OP_IMM => Imm(unsafe { value.imm }), ARM_OP_MEM => Mem(ArmOpMem(unsafe { value.mem })), ARM_OP_FP => Fp(unsafe { value.fp }), ARM_OP_CIMM => Cimm(unsafe { value.imm }), ARM_OP_PIMM => Pimm(unsafe { value.imm }), ARM_OP_SETEND => Setend(unsafe { value.setend }), ARM_OP_SYSREG => SysReg(RegId(unsafe { value.reg } as RegIdInt)), } } } /// ARM operand #[derive(Clone, Debug, PartialEq)] pub struct ArmOperand { /// Vector Index for some vector operands pub vector_index: Option<u32>, /// Whether operand is subtracted pub subtracted: bool, pub shift: ArmShift, /// Operand type pub op_type: ArmOperandType, } /// ARM operand #[derive(Clone, Debug, PartialEq)] pub enum ArmOperandType { /// Register Reg(RegId), /// Immediate Imm(i32), /// Memory Mem(ArmOpMem), /// Floating point Fp(f64), /// C-IMM Cimm(i32), /// P-IMM Pimm(i32), /// SETEND instruction endianness Setend(ArmSetendType), /// Sysreg SysReg(RegId), /// Invalid Invalid, } /// ARM memory operand #[derive(Debug, Copy, Clone)] pub struct ArmOpMem(pub(crate) arm_op_mem); impl<'a> ArmInsnDetail<'a> { /// Whether the instruction is a user mode pub fn usermode(&self) -> bool { self.0.usermode } /// Vector size pub fn vector_size(&self) -> i32 { self.0.vector_size as i32 } /// Type of vector data pub fn vector_data(&self) -> ArmVectorData { self.0.vector_data } /// CPS mode for CPS instruction pub fn cps_mode(&self) -> ArmCPSMode { self.0.cps_mode } /// CPS flag for CPS instruction pub fn cps_flag(&self) -> ArmCPSFlag { self.0.cps_flag } /// Condition codes pub fn cc(&self) -> ArmCC { self.0.cc } /// Whether this insn updates flags pub fn update_flags(&self) -> bool { self.0.update_flags } /// Whether writeback is required pub fn writeback(&self) -> bool { self.0.writeback } /// Memory barrier pub fn mem_barrier(&self) -> ArmMemBarrier { self.0.mem_barrier } } impl_PartialEq_repr_fields!(ArmInsnDetail<'a> [ 'a ]; usermode, vector_size, vector_data, cps_mode, cps_flag, cc, update_flags, writeback, mem_barrier, operands ); impl ArmOpMem { /// Base register pub fn base(&self) -> RegId { RegId(self.0.base as RegIdInt) } /// Index value pub fn
(&self) -> RegId { RegId(self.0.index as RegIdInt) } /// Scale for index register (can be 1, or -1) pub fn scale(&self) -> i32 { self.0.scale as i32 } /// Disp value pub fn disp(&self) -> i32 { self.0.disp as i32 } } impl_PartialEq_repr_fields!(ArmOpMem; base, index, scale, disp ); impl cmp::Eq for ArmOpMem {} impl Default for ArmOperand { fn default() -> Self { ArmOperand { vector_index: None, subtracted: false, shift: ArmShift::Invalid, op_type: ArmOperandType::Invalid } } } impl<'a> From<&'a cs_arm_op> for ArmOperand { fn from(op: &cs_arm_op) -> ArmOperand { let shift = ArmShift::new(op.shift.type_, op.shift.value); let op_type = ArmOperandType::new(op.type_, op.__bindgen_anon_1); let vector_index = if op.vector_index >= 0 { Some(op.vector_index as u32) } else { None }; ArmOperand { vector_index, shift, op_type, subtracted: op.subtracted, } } } def_arch_details_struct!( InsnDetail = ArmInsnDetail; Operand = ArmOperand; OperandIterator = ArmOperandIterator; OperandIteratorLife = ArmOperandIterator<'a>; [ pub struct ArmOperandIterator<'a>(slice::Iter<'a, cs_arm_op>); ] cs_arch_op = cs_arm_op; cs_arch = cs_arm; ); #[cfg(test)] mod test { use super::*; use capstone_sys::*; #[test] fn test_armshift() { use super::arm_shifter::*; use super::ArmShift::*; use libc::c_uint; fn t(shift_type_value: (arm_shifter, c_uint), arm_shift: ArmShift) { let (shift_type, value) = shift_type_value; assert_eq!(arm_shift, ArmShift::new(shift_type, value)); } t((ARM_SFT_INVALID, 0), Invalid); t((ARM_SFT_ASR, 0), Asr(0)); t((ARM_SFT_ASR_REG, 42), AsrReg(RegId(42))); t((ARM_SFT_RRX_REG, 42), RrxReg(RegId(42))); } #[test] fn test_arm_op_type() { use super::arm_op_type::*; use super::ArmOperandType::*; fn t( op_type_value: (arm_op_type, cs_arm_op__bindgen_ty_2), expected_op_type: ArmOperandType, ) { let (op_type, op_value) = op_type_value; let op_type = ArmOperandType::new(op_type, op_value); assert_eq!(expected_op_type, op_type); } t( (ARM_OP_INVALID, cs_arm_op__bindgen_ty_2 { reg: 0 }), Invalid, ); t( (ARM_OP_REG, cs_arm_op__bindgen_ty_2 { reg: 0 }), Reg(RegId(0)), ); } #[test] fn test_arm_insn_detail_eq() { let a1 = cs_arm { usermode: false, vector_size: 0, vector_data: arm_vectordata_type::ARM_VECTORDATA_INVALID, cps_mode: arm_cpsmode_type::ARM_CPSMODE_INVALID, cps_flag: arm_cpsflag_type::ARM_CPSFLAG_INVALID, cc: arm_cc::ARM_CC_INVALID, update_flags: false, writeback: false, mem_barrier: arm_mem_barrier::ARM_MB_INVALID, op_count: 0, operands: [ cs_arm_op { vector_index: 0, shift: cs_arm_op__bindgen_ty_1 { type_: arm_shifter::ARM_SFT_INVALID, value: 0 }, type_: arm_op_type::ARM_OP_INVALID, __bindgen_anon_1: cs_arm_op__bindgen_ty_2 { imm: 0 }, subtracted: false, access: 0, neon_lane: 0, } ; 36] }; let a2 = cs_arm { usermode: true, ..a1 }; let a3 = cs_arm { op_count: 20, ..a1 }; let a4 = cs_arm { op_count: 19, ..a1 }; let a4_clone = a4.clone(); assert_eq!(ArmInsnDetail(&a1), ArmInsnDetail(&a1)); assert_ne!(ArmInsnDetail(&a1), ArmInsnDetail(&a2)); assert_ne!(ArmInsnDetail(&a1), ArmInsnDetail(&a3)); assert_ne!(ArmInsnDetail(&a3), ArmInsnDetail(&a4)); assert_eq!(ArmInsnDetail(&a4), ArmInsnDetail(&a4_clone)); } }
index
identifier_name
utils.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Utilities and helper functions.""" import abc import contextlib import datetime import functools import hashlib import inspect import logging as py_logging import os import pyclbr import random import re import shutil import socket import stat import sys import tempfile import time import types from xml.dom import minidom from xml.parsers import expat from xml import sax from xml.sax import expatreader from xml.sax import saxutils from os_brick.initiator import connector from oslo_concurrency import lockutils from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import log as logging from oslo_utils import encodeutils from oslo_utils import importutils from oslo_utils import strutils from oslo_utils import timeutils import retrying import six from cinder import exception from cinder.i18n import _, _LE, _LW CONF = cfg.CONF LOG = logging.getLogger(__name__) ISO_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S" PERFECT_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f" VALID_TRACE_FLAGS = {'method', 'api'} TRACE_METHOD = False TRACE_API = False synchronized = lockutils.synchronized_with_prefix('cinder-') def find_config(config_path): """Find a configuration file using the given hint. :param config_path: Full or relative path to the config. :returns: Full path of the config, if it exists. :raises: `cinder.exception.ConfigNotFound` """ possible_locations = [ config_path, os.path.join(CONF.state_path, "etc", "cinder", config_path), os.path.join(CONF.state_path, "etc", config_path), os.path.join(CONF.state_path, config_path), "/etc/cinder/%s" % config_path, ] for path in possible_locations: if os.path.exists(path): return os.path.abspath(path) raise exception.ConfigNotFound(path=os.path.abspath(config_path)) def as_int(obj, quiet=True): # Try "2" -> 2 try: return int(obj) except (ValueError, TypeError): pass # Try "2.5" -> 2 try: return int(float(obj)) except (ValueError, TypeError): pass # Eck, not sure what this is then. if not quiet: raise TypeError(_("Can not translate %s to integer.") % (obj)) return obj def is_int_like(val): """Check if a value looks like an int.""" try: return str(int(val)) == str(val) except Exception: return False def check_exclusive_options(**kwargs): """Checks that only one of the provided options is actually not-none. Iterates over all the kwargs passed in and checks that only one of said arguments is not-none, if more than one is not-none then an exception will be raised with the names of those arguments who were not-none. """ if not kwargs: return pretty_keys = kwargs.pop("pretty_keys", True) exclusive_options = {} for (k, v) in kwargs.items(): if v is not None: exclusive_options[k] = True if len(exclusive_options) > 1: # Change the format of the names from pythonic to # something that is more readable. # # Ex: 'the_key' -> 'the key' if pretty_keys: names = [k.replace('_', ' ') for k in kwargs.keys()] else: names = kwargs.keys() names = ", ".join(sorted(names)) msg = (_("May specify only one of %s") % (names)) raise exception.InvalidInput(reason=msg) def execute(*cmd, **kwargs): """Convenience wrapper around oslo's execute() method.""" if 'run_as_root' in kwargs and 'root_helper' not in kwargs: kwargs['root_helper'] = get_root_helper() return processutils.execute(*cmd, **kwargs) def check_ssh_injection(cmd_list): ssh_injection_pattern = ['`', '$', '|', '||', ';', '&', '&&', '>', '>>', '<'] # Check whether injection attacks exist for arg in cmd_list: arg = arg.strip() # Check for matching quotes on the ends is_quoted = re.match('^(?P<quote>[\'"])(?P<quoted>.*)(?P=quote)$', arg) if is_quoted: # Check for unescaped quotes within the quoted argument quoted = is_quoted.group('quoted') if quoted: if (re.match('[\'"]', quoted) or re.search('[^\\\\][\'"]', quoted)): raise exception.SSHInjectionThreat(command=cmd_list) else: # We only allow spaces within quoted arguments, and that # is the only special character allowed within quotes if len(arg.split()) > 1: raise exception.SSHInjectionThreat(command=cmd_list) # Second, check whether danger character in command. So the shell # special operator must be a single argument. for c in ssh_injection_pattern: if c not in arg:
result = arg.find(c) if not result == -1: if result == 0 or not arg[result - 1] == '\\': raise exception.SSHInjectionThreat(command=cmd_list) def create_channel(client, width, height): """Invoke an interactive shell session on server.""" channel = client.invoke_shell() channel.resize_pty(width, height) return channel def cinderdir(): import cinder return os.path.abspath(cinder.__file__).split('cinder/__init__.py')[0] def last_completed_audit_period(unit=None): """This method gives you the most recently *completed* audit period. arguments: units: string, one of 'hour', 'day', 'month', 'year' Periods normally begin at the beginning (UTC) of the period unit (So a 'day' period begins at midnight UTC, a 'month' unit on the 1st, a 'year' on Jan, 1) unit string may be appended with an optional offset like so: 'day@18' This will begin the period at 18:00 UTC. 'month@15' starts a monthly period on the 15th, and year@3 begins a yearly one on March 1st. returns: 2 tuple of datetimes (begin, end) The begin timestamp of this audit period is the same as the end of the previous. """ if not unit: unit = CONF.volume_usage_audit_period offset = 0 if '@' in unit: unit, offset = unit.split("@", 1) offset = int(offset) rightnow = timeutils.utcnow() if unit not in ('month', 'day', 'year', 'hour'): raise ValueError('Time period must be hour, day, month or year') if unit == 'month': if offset == 0: offset = 1 end = datetime.datetime(day=offset, month=rightnow.month, year=rightnow.year) if end >= rightnow: year = rightnow.year if 1 >= rightnow.month: year -= 1 month = 12 + (rightnow.month - 1) else: month = rightnow.month - 1 end = datetime.datetime(day=offset, month=month, year=year) year = end.year if 1 >= end.month: year -= 1 month = 12 + (end.month - 1) else: month = end.month - 1 begin = datetime.datetime(day=offset, month=month, year=year) elif unit == 'year': if offset == 0: offset = 1 end = datetime.datetime(day=1, month=offset, year=rightnow.year) if end >= rightnow: end = datetime.datetime(day=1, month=offset, year=rightnow.year - 1) begin = datetime.datetime(day=1, month=offset, year=rightnow.year - 2) else: begin = datetime.datetime(day=1, month=offset, year=rightnow.year - 1) elif unit == 'day': end = datetime.datetime(hour=offset, day=rightnow.day, month=rightnow.month, year=rightnow.year) if end >= rightnow: end = end - datetime.timedelta(days=1) begin = end - datetime.timedelta(days=1) elif unit == 'hour': end = rightnow.replace(minute=offset, second=0, microsecond=0) if end >= rightnow: end = end - datetime.timedelta(hours=1) begin = end - datetime.timedelta(hours=1) return (begin, end) def list_of_dicts_to_dict(seq, key): """Convert list of dicts to a indexted dict. Takes a list of dicts, and converts it a nested dict indexed by <key> :param seq: list of dicts :parm key: key in dicts to index by example: lst = [{'id': 1, ...}, {'id': 2, ...}...] key = 'id' returns {1:{'id': 1, ...}, 2:{'id':2, ...} """ return {d[key]: dict(d, index=d[key]) for (i, d) in enumerate(seq)} class ProtectedExpatParser(expatreader.ExpatParser): """An expat parser which disables DTD's and entities by default.""" def __init__(self, forbid_dtd=True, forbid_entities=True, *args, **kwargs): # Python 2.x old style class expatreader.ExpatParser.__init__(self, *args, **kwargs) self.forbid_dtd = forbid_dtd self.forbid_entities = forbid_entities def start_doctype_decl(self, name, sysid, pubid, has_internal_subset): raise ValueError("Inline DTD forbidden") def entity_decl(self, entityName, is_parameter_entity, value, base, systemId, publicId, notationName): raise ValueError("<!ENTITY> forbidden") def unparsed_entity_decl(self, name, base, sysid, pubid, notation_name): # expat 1.2 raise ValueError("<!ENTITY> forbidden") def reset(self): expatreader.ExpatParser.reset(self) if self.forbid_dtd: self._parser.StartDoctypeDeclHandler = self.start_doctype_decl if self.forbid_entities: self._parser.EntityDeclHandler = self.entity_decl self._parser.UnparsedEntityDeclHandler = self.unparsed_entity_decl def safe_minidom_parse_string(xml_string): """Parse an XML string using minidom safely. """ try: return minidom.parseString(xml_string, parser=ProtectedExpatParser()) except sax.SAXParseException: raise expat.ExpatError() def xhtml_escape(value): """Escapes a string so it is valid within XML or XHTML.""" return saxutils.escape(value, {'"': '&quot;', "'": '&apos;'}) def get_from_path(items, path): """Returns a list of items matching the specified path. Takes an XPath-like expression e.g. prop1/prop2/prop3, and for each item in items, looks up items[prop1][prop2][prop3]. Like XPath, if any of the intermediate results are lists it will treat each list item individually. A 'None' in items or any child expressions will be ignored, this function will not throw because of None (anywhere) in items. The returned list will contain no None values. """ if path is None: raise exception.Error('Invalid mini_xpath') (first_token, sep, remainder) = path.partition('/') if first_token == '': raise exception.Error('Invalid mini_xpath') results = [] if items is None: return results if not isinstance(items, list): # Wrap single objects in a list items = [items] for item in items: if item is None: continue get_method = getattr(item, 'get', None) if get_method is None: continue child = get_method(first_token) if child is None: continue if isinstance(child, list): # Flatten intermediate lists for x in child: results.append(x) else: results.append(child) if not sep: # No more tokens return results else: return get_from_path(results, remainder) def is_valid_boolstr(val): """Check if the provided string is a valid bool string or not.""" val = str(val).lower() return (val == 'true' or val == 'false' or val == 'yes' or val == 'no' or val == 'y' or val == 'n' or val == '1' or val == '0') def is_none_string(val): """Check if a string represents a None value.""" if not isinstance(val, six.string_types): return False return val.lower() == 'none' def monkey_patch(): """Patches decorators for all functions in a specified module. If the CONF.monkey_patch set as True, this function patches a decorator for all functions in specified modules. You can set decorators for each modules using CONF.monkey_patch_modules. The format is "Module path:Decorator function". Example: 'cinder.api.ec2.cloud:' \ cinder.openstack.common.notifier.api.notify_decorator' Parameters of the decorator is as follows. (See cinder.openstack.common.notifier.api.notify_decorator) :param name: name of the function :param function: object of the function """ # If CONF.monkey_patch is not True, this function do nothing. if not CONF.monkey_patch: return # Get list of modules and decorators for module_and_decorator in CONF.monkey_patch_modules: module, decorator_name = module_and_decorator.split(':') # import decorator function decorator = importutils.import_class(decorator_name) __import__(module) # Retrieve module information using pyclbr module_data = pyclbr.readmodule_ex(module) for key in module_data.keys(): # set the decorator for the class methods if isinstance(module_data[key], pyclbr.Class): clz = importutils.import_class("%s.%s" % (module, key)) for method, func in inspect.getmembers(clz, inspect.ismethod): setattr( clz, method, decorator("%s.%s.%s" % (module, key, method), func)) # set the decorator for the function if isinstance(module_data[key], pyclbr.Function): func = importutils.import_class("%s.%s" % (module, key)) setattr(sys.modules[module], key, decorator("%s.%s" % (module, key), func)) def make_dev_path(dev, partition=None, base='/dev'): """Return a path to a particular device. >>> make_dev_path('xvdc') /dev/xvdc >>> make_dev_path('xvdc', 1) /dev/xvdc1 """ path = os.path.join(base, dev) if partition: path += str(partition) return path def sanitize_hostname(hostname): """Return a hostname which conforms to RFC-952 and RFC-1123 specs.""" if six.PY3: hostname = hostname.encode('latin-1', 'ignore') hostname = hostname.decode('latin-1') else: if isinstance(hostname, six.text_type): hostname = hostname.encode('latin-1', 'ignore') hostname = re.sub('[ _]', '-', hostname) hostname = re.sub('[^\w.-]+', '', hostname) hostname = hostname.lower() hostname = hostname.strip('.-') return hostname def hash_file(file_like_object): """Generate a hash for the contents of a file.""" checksum = hashlib.sha1() any(map(checksum.update, iter(lambda: file_like_object.read(32768), b''))) return checksum.hexdigest() def service_is_up(service): """Check whether a service is up based on last heartbeat.""" last_heartbeat = service['updated_at'] or service['created_at'] # Timestamps in DB are UTC. elapsed = (timeutils.utcnow(with_timezone=True) - last_heartbeat).total_seconds() return abs(elapsed) <= CONF.service_down_time def read_file_as_root(file_path): """Secure helper to read file as root.""" try: out, _err = execute('cat', file_path, run_as_root=True) return out except processutils.ProcessExecutionError: raise exception.FileNotFound(file_path=file_path) @contextlib.contextmanager def temporary_chown(path, owner_uid=None): """Temporarily chown a path. :params owner_uid: UID of temporary owner (defaults to current user) """ if owner_uid is None: owner_uid = os.getuid() orig_uid = os.stat(path).st_uid if orig_uid != owner_uid: execute('chown', owner_uid, path, run_as_root=True) try: yield finally: if orig_uid != owner_uid: execute('chown', orig_uid, path, run_as_root=True) @contextlib.contextmanager def tempdir(**kwargs): tmpdir = tempfile.mkdtemp(**kwargs) try: yield tmpdir finally: try: shutil.rmtree(tmpdir) except OSError as e: LOG.debug('Could not remove tmpdir: %s', six.text_type(e)) def walk_class_hierarchy(clazz, encountered=None): """Walk class hierarchy, yielding most derived classes first.""" if not encountered: encountered = [] for subclass in clazz.__subclasses__(): if subclass not in encountered: encountered.append(subclass) # drill down to leaves first for subsubclass in walk_class_hierarchy(subclass, encountered): yield subsubclass yield subclass def get_root_helper(): return 'sudo cinder-rootwrap %s' % CONF.rootwrap_config def brick_get_connector_properties(multipath=False, enforce_multipath=False): """Wrapper to automatically set root_helper in brick calls. :param multipath: A boolean indicating whether the connector can support multipath. :param enforce_multipath: If True, it raises exception when multipath=True is specified but multipathd is not running. If False, it falls back to multipath=False when multipathd is not running. """ root_helper = get_root_helper() return connector.get_connector_properties(root_helper, CONF.my_ip, multipath, enforce_multipath) def brick_get_connector(protocol, driver=None, execute=processutils.execute, use_multipath=False, device_scan_attempts=3, *args, **kwargs): """Wrapper to get a brick connector object. This automatically populates the required protocol as well as the root_helper needed to execute commands. """ root_helper = get_root_helper() return connector.InitiatorConnector.factory(protocol, root_helper, driver=driver, execute=execute, use_multipath=use_multipath, device_scan_attempts= device_scan_attempts, *args, **kwargs) def require_driver_initialized(driver): """Verifies if `driver` is initialized If the driver is not initialized, an exception will be raised. :params driver: The driver instance. :raises: `exception.DriverNotInitialized` """ # we can't do anything if the driver didn't init if not driver.initialized: driver_name = driver.__class__.__name__ LOG.error(_LE("Volume driver %s not initialized"), driver_name) raise exception.DriverNotInitialized() def get_file_mode(path): """This primarily exists to make unit testing easier.""" return stat.S_IMODE(os.stat(path).st_mode) def get_file_gid(path): """This primarily exists to make unit testing easier.""" return os.stat(path).st_gid def get_file_size(path): """Returns the file size.""" return os.stat(path).st_size def _get_disk_of_partition(devpath, st=None): """Gets a disk device path and status from partition path. Returns a disk device path from a partition device path, and stat for the device. If devpath is not a partition, devpath is returned as it is. For example, '/dev/sda' is returned for '/dev/sda1', and '/dev/disk1' is for '/dev/disk1p1' ('p' is prepended to the partition number if the disk name ends with numbers). """ diskpath = re.sub('(?:(?<=\d)p)?\d+$', '', devpath) if diskpath != devpath: try: st_disk = os.stat(diskpath) if stat.S_ISBLK(st_disk.st_mode): return (diskpath, st_disk) except OSError: pass # devpath is not a partition if st is None: st = os.stat(devpath) return (devpath, st) def get_bool_param(param_string, params): param = params.get(param_string, False) if not is_valid_boolstr(param): msg = _('Value %(param)s for %(param_string)s is not a ' 'boolean.') % {'param': param, 'param_string': param_string} raise exception.InvalidParameterValue(err=msg) return strutils.bool_from_string(param, strict=True) def get_blkdev_major_minor(path, lookup_for_file=True): """Get 'major:minor' number of block device. Get the device's 'major:minor' number of a block device to control I/O ratelimit of the specified path. If lookup_for_file is True and the path is a regular file, lookup a disk device which the file lies on and returns the result for the device. """ st = os.stat(path) if stat.S_ISBLK(st.st_mode): path, st = _get_disk_of_partition(path, st) return '%d:%d' % (os.major(st.st_rdev), os.minor(st.st_rdev)) elif stat.S_ISCHR(st.st_mode): # No I/O ratelimit control is provided for character devices return None elif lookup_for_file: # lookup the mounted disk which the file lies on out, _err = execute('df', path) devpath = out.split("\n")[1].split()[0] if devpath[0] is not '/': # the file is on a network file system return None return get_blkdev_major_minor(devpath, False) else: msg = _("Unable to get a block device for file \'%s\'") % path raise exception.Error(msg) def check_string_length(value, name, min_length=0, max_length=None): """Check the length of specified string. :param value: the value of the string :param name: the name of the string :param min_length: the min_length of the string :param max_length: the max_length of the string """ if not isinstance(value, six.string_types): msg = _("%s is not a string or unicode") % name raise exception.InvalidInput(message=msg) if len(value) < min_length: msg = _("%(name)s has a minimum character requirement of " "%(min_length)s.") % {'name': name, 'min_length': min_length} raise exception.InvalidInput(message=msg) if max_length and len(value) > max_length: msg = _("%(name)s has more than %(max_length)s " "characters.") % {'name': name, 'max_length': max_length} raise exception.InvalidInput(message=msg) _visible_admin_metadata_keys = ['readonly', 'attached_mode'] def add_visible_admin_metadata(volume): """Add user-visible admin metadata to regular metadata. Extracts the admin metadata keys that are to be made visible to non-administrators, and adds them to the regular metadata structure for the passed-in volume. """ visible_admin_meta = {} if volume.get('volume_admin_metadata'): if isinstance(volume['volume_admin_metadata'], dict): volume_admin_metadata = volume['volume_admin_metadata'] for key in volume_admin_metadata: if key in _visible_admin_metadata_keys: visible_admin_meta[key] = volume_admin_metadata[key] else: for item in volume['volume_admin_metadata']: if item['key'] in _visible_admin_metadata_keys: visible_admin_meta[item['key']] = item['value'] # avoid circular ref when volume is a Volume instance elif (volume.get('admin_metadata') and isinstance(volume.get('admin_metadata'), dict)): for key in _visible_admin_metadata_keys: if key in volume['admin_metadata'].keys(): visible_admin_meta[key] = volume['admin_metadata'][key] if not visible_admin_meta: return # NOTE(zhiyan): update visible administration metadata to # volume metadata, administration metadata will rewrite existing key. if volume.get('volume_metadata'): orig_meta = list(volume.get('volume_metadata')) for item in orig_meta: if item['key'] in visible_admin_meta.keys(): item['value'] = visible_admin_meta.pop(item['key']) for key, value in visible_admin_meta.items(): orig_meta.append({'key': key, 'value': value}) volume['volume_metadata'] = orig_meta # avoid circular ref when vol is a Volume instance elif (volume.get('metadata') and isinstance(volume.get('metadata'), dict)): volume['metadata'].update(visible_admin_meta) else: volume['metadata'] = visible_admin_meta def remove_invalid_filter_options(context, filters, allowed_search_options): """Remove search options that are not valid for non-admin API/context.""" if context.is_admin: # Allow all options return # Otherwise, strip out all unknown options unknown_options = [opt for opt in filters if opt not in allowed_search_options] bad_options = ", ".join(unknown_options) LOG.debug("Removing options '%s' from query.", bad_options) for opt in unknown_options: del filters[opt] def is_blk_device(dev): try: if stat.S_ISBLK(os.stat(dev).st_mode): return True return False except Exception: LOG.debug('Path %s not found in is_blk_device check', dev) return False def retry(exceptions, interval=1, retries=3, backoff_rate=2, wait_random=False): def _retry_on_exception(e): return isinstance(e, exceptions) def _backoff_sleep(previous_attempt_number, delay_since_first_attempt_ms): exp = backoff_rate ** previous_attempt_number wait_for = interval * exp if wait_random: random.seed() wait_val = random.randrange(interval * 1000.0, wait_for * 1000.0) else: wait_val = wait_for * 1000.0 LOG.debug("Sleeping for %s seconds", (wait_val / 1000.0)) return wait_val def _print_stop(previous_attempt_number, delay_since_first_attempt_ms): delay_since_first_attempt = delay_since_first_attempt_ms / 1000.0 LOG.debug("Failed attempt %s", previous_attempt_number) LOG.debug("Have been at this for %s seconds", delay_since_first_attempt) return previous_attempt_number == retries if retries < 1: raise ValueError('Retries must be greater than or ' 'equal to 1 (received: %s). ' % retries) def _decorator(f): @six.wraps(f) def _wrapper(*args, **kwargs): r = retrying.Retrying(retry_on_exception=_retry_on_exception, wait_func=_backoff_sleep, stop_func=_print_stop) return r.call(f, *args, **kwargs) return _wrapper return _decorator def convert_version_to_int(version): try: if isinstance(version, six.string_types): version = convert_version_to_tuple(version) if isinstance(version, tuple): return six.moves.reduce(lambda x, y: (x * 1000) + y, version) except Exception: msg = _("Version %s is invalid.") % version raise exception.CinderException(msg) def convert_version_to_str(version_int): version_numbers = [] factor = 1000 while version_int != 0: version_number = version_int - (version_int // factor * factor) version_numbers.insert(0, six.text_type(version_number)) version_int = version_int // factor return '.'.join(map(str, version_numbers)) def convert_version_to_tuple(version_str): return tuple(int(part) for part in version_str.split('.')) def convert_str(text): """Convert to native string. Convert bytes and Unicode strings to native strings: * convert to bytes on Python 2: encode Unicode using encodeutils.safe_encode() * convert to Unicode on Python 3: decode bytes from UTF-8 """ if six.PY2: return encodeutils.safe_encode(text) else: if isinstance(text, bytes): return text.decode('utf-8') else: return text def trace_method(f): """Decorates a function if TRACE_METHOD is true.""" @functools.wraps(f) def trace_method_logging_wrapper(*args, **kwargs): if TRACE_METHOD: return trace(f)(*args, **kwargs) return f(*args, **kwargs) return trace_method_logging_wrapper def trace_api(f): """Decorates a function if TRACE_API is true.""" @functools.wraps(f) def trace_api_logging_wrapper(*args, **kwargs): if TRACE_API: return trace(f)(*args, **kwargs) return f(*args, **kwargs) return trace_api_logging_wrapper def trace(f): """Trace calls to the decorated function. This decorator should always be defined as the outermost decorator so it is defined last. This is important so it does not interfere with other decorators. Using this decorator on a function will cause its execution to be logged at `DEBUG` level with arguments, return values, and exceptions. :returns a function decorator """ func_name = f.__name__ @functools.wraps(f) def trace_logging_wrapper(*args, **kwargs): if len(args) > 0: maybe_self = args[0] else: maybe_self = kwargs.get('self', None) if maybe_self and hasattr(maybe_self, '__module__'): logger = logging.getLogger(maybe_self.__module__) else: logger = LOG # NOTE(ameade): Don't bother going any further if DEBUG log level # is not enabled for the logger. if not logger.isEnabledFor(py_logging.DEBUG): return f(*args, **kwargs) all_args = inspect.getcallargs(f, *args, **kwargs) logger.debug('==> %(func)s: call %(all_args)r', {'func': func_name, 'all_args': all_args}) start_time = time.time() * 1000 try: result = f(*args, **kwargs) except Exception as exc: total_time = int(round(time.time() * 1000)) - start_time logger.debug('<== %(func)s: exception (%(time)dms) %(exc)r', {'func': func_name, 'time': total_time, 'exc': exc}) raise total_time = int(round(time.time() * 1000)) - start_time logger.debug('<== %(func)s: return (%(time)dms) %(result)r', {'func': func_name, 'time': total_time, 'result': result}) return result return trace_logging_wrapper class TraceWrapperMetaclass(type): """Metaclass that wraps all methods of a class with trace_method. This metaclass will cause every function inside of the class to be decorated with the trace_method decorator. To use the metaclass you define a class like so: @six.add_metaclass(utils.TraceWrapperMetaclass) class MyClass(object): """ def __new__(meta, classname, bases, classDict): newClassDict = {} for attributeName, attribute in classDict.items(): if isinstance(attribute, types.FunctionType): # replace it with a wrapped version attribute = functools.update_wrapper(trace_method(attribute), attribute) newClassDict[attributeName] = attribute return type.__new__(meta, classname, bases, newClassDict) class TraceWrapperWithABCMetaclass(abc.ABCMeta, TraceWrapperMetaclass): """Metaclass that wraps all methods of a class with trace.""" pass def setup_tracing(trace_flags): """Set global variables for each trace flag. Sets variables TRACE_METHOD and TRACE_API, which represent whether to log method and api traces. :param trace_flags: a list of strings """ global TRACE_METHOD global TRACE_API try: trace_flags = [flag.strip() for flag in trace_flags] except TypeError: # Handle when trace_flags is None or a test mock trace_flags = [] for invalid_flag in (set(trace_flags) - VALID_TRACE_FLAGS): LOG.warning(_LW('Invalid trace flag: %s'), invalid_flag) TRACE_METHOD = 'method' in trace_flags TRACE_API = 'api' in trace_flags def resolve_hostname(hostname): """Resolves host name to IP address. Resolves a host name (my.data.point.com) to an IP address (10.12.143.11). This routine also works if the data passed in hostname is already an IP. In this case, the same IP address will be returned. :param hostname: Host name to resolve. :return: IP Address for Host name. """ result = socket.getaddrinfo(hostname, None)[0] (family, socktype, proto, canonname, sockaddr) = result LOG.debug('Asked to resolve hostname %(host)s and got IP %(ip)s.', {'host': hostname, 'ip': sockaddr[0]}) return sockaddr[0]
continue
conditional_block
utils.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Utilities and helper functions.""" import abc import contextlib import datetime import functools import hashlib import inspect import logging as py_logging import os import pyclbr import random import re import shutil import socket import stat import sys import tempfile import time import types from xml.dom import minidom from xml.parsers import expat from xml import sax from xml.sax import expatreader from xml.sax import saxutils from os_brick.initiator import connector from oslo_concurrency import lockutils from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import log as logging from oslo_utils import encodeutils from oslo_utils import importutils from oslo_utils import strutils from oslo_utils import timeutils import retrying import six from cinder import exception from cinder.i18n import _, _LE, _LW CONF = cfg.CONF LOG = logging.getLogger(__name__) ISO_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S" PERFECT_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f" VALID_TRACE_FLAGS = {'method', 'api'} TRACE_METHOD = False TRACE_API = False synchronized = lockutils.synchronized_with_prefix('cinder-') def find_config(config_path): """Find a configuration file using the given hint. :param config_path: Full or relative path to the config. :returns: Full path of the config, if it exists. :raises: `cinder.exception.ConfigNotFound` """ possible_locations = [ config_path, os.path.join(CONF.state_path, "etc", "cinder", config_path), os.path.join(CONF.state_path, "etc", config_path), os.path.join(CONF.state_path, config_path), "/etc/cinder/%s" % config_path, ] for path in possible_locations: if os.path.exists(path): return os.path.abspath(path) raise exception.ConfigNotFound(path=os.path.abspath(config_path)) def as_int(obj, quiet=True): # Try "2" -> 2 try: return int(obj) except (ValueError, TypeError): pass # Try "2.5" -> 2 try: return int(float(obj)) except (ValueError, TypeError): pass # Eck, not sure what this is then. if not quiet: raise TypeError(_("Can not translate %s to integer.") % (obj)) return obj def is_int_like(val): """Check if a value looks like an int.""" try: return str(int(val)) == str(val) except Exception: return False def check_exclusive_options(**kwargs): """Checks that only one of the provided options is actually not-none. Iterates over all the kwargs passed in and checks that only one of said arguments is not-none, if more than one is not-none then an exception will be raised with the names of those arguments who were not-none. """ if not kwargs: return pretty_keys = kwargs.pop("pretty_keys", True) exclusive_options = {} for (k, v) in kwargs.items(): if v is not None: exclusive_options[k] = True if len(exclusive_options) > 1: # Change the format of the names from pythonic to # something that is more readable. # # Ex: 'the_key' -> 'the key' if pretty_keys: names = [k.replace('_', ' ') for k in kwargs.keys()] else: names = kwargs.keys() names = ", ".join(sorted(names)) msg = (_("May specify only one of %s") % (names)) raise exception.InvalidInput(reason=msg) def execute(*cmd, **kwargs): """Convenience wrapper around oslo's execute() method.""" if 'run_as_root' in kwargs and 'root_helper' not in kwargs: kwargs['root_helper'] = get_root_helper() return processutils.execute(*cmd, **kwargs) def check_ssh_injection(cmd_list): ssh_injection_pattern = ['`', '$', '|', '||', ';', '&', '&&', '>', '>>', '<'] # Check whether injection attacks exist for arg in cmd_list: arg = arg.strip() # Check for matching quotes on the ends is_quoted = re.match('^(?P<quote>[\'"])(?P<quoted>.*)(?P=quote)$', arg) if is_quoted: # Check for unescaped quotes within the quoted argument quoted = is_quoted.group('quoted') if quoted: if (re.match('[\'"]', quoted) or re.search('[^\\\\][\'"]', quoted)): raise exception.SSHInjectionThreat(command=cmd_list) else: # We only allow spaces within quoted arguments, and that # is the only special character allowed within quotes if len(arg.split()) > 1: raise exception.SSHInjectionThreat(command=cmd_list) # Second, check whether danger character in command. So the shell # special operator must be a single argument. for c in ssh_injection_pattern: if c not in arg: continue result = arg.find(c) if not result == -1: if result == 0 or not arg[result - 1] == '\\': raise exception.SSHInjectionThreat(command=cmd_list) def create_channel(client, width, height): """Invoke an interactive shell session on server.""" channel = client.invoke_shell() channel.resize_pty(width, height) return channel def cinderdir(): import cinder return os.path.abspath(cinder.__file__).split('cinder/__init__.py')[0] def last_completed_audit_period(unit=None): """This method gives you the most recently *completed* audit period. arguments: units: string, one of 'hour', 'day', 'month', 'year' Periods normally begin at the beginning (UTC) of the period unit (So a 'day' period begins at midnight UTC, a 'month' unit on the 1st, a 'year' on Jan, 1) unit string may be appended with an optional offset like so: 'day@18' This will begin the period at 18:00 UTC. 'month@15' starts a monthly period on the 15th, and year@3 begins a yearly one on March 1st. returns: 2 tuple of datetimes (begin, end) The begin timestamp of this audit period is the same as the end of the previous. """ if not unit: unit = CONF.volume_usage_audit_period offset = 0 if '@' in unit: unit, offset = unit.split("@", 1) offset = int(offset) rightnow = timeutils.utcnow() if unit not in ('month', 'day', 'year', 'hour'): raise ValueError('Time period must be hour, day, month or year') if unit == 'month': if offset == 0: offset = 1 end = datetime.datetime(day=offset, month=rightnow.month, year=rightnow.year) if end >= rightnow: year = rightnow.year if 1 >= rightnow.month: year -= 1 month = 12 + (rightnow.month - 1) else: month = rightnow.month - 1 end = datetime.datetime(day=offset, month=month, year=year) year = end.year if 1 >= end.month: year -= 1 month = 12 + (end.month - 1) else: month = end.month - 1 begin = datetime.datetime(day=offset, month=month, year=year) elif unit == 'year': if offset == 0: offset = 1 end = datetime.datetime(day=1, month=offset, year=rightnow.year) if end >= rightnow: end = datetime.datetime(day=1, month=offset, year=rightnow.year - 1) begin = datetime.datetime(day=1, month=offset, year=rightnow.year - 2) else: begin = datetime.datetime(day=1, month=offset, year=rightnow.year - 1) elif unit == 'day': end = datetime.datetime(hour=offset, day=rightnow.day, month=rightnow.month, year=rightnow.year) if end >= rightnow: end = end - datetime.timedelta(days=1) begin = end - datetime.timedelta(days=1) elif unit == 'hour': end = rightnow.replace(minute=offset, second=0, microsecond=0) if end >= rightnow: end = end - datetime.timedelta(hours=1) begin = end - datetime.timedelta(hours=1) return (begin, end) def list_of_dicts_to_dict(seq, key): """Convert list of dicts to a indexted dict. Takes a list of dicts, and converts it a nested dict indexed by <key> :param seq: list of dicts :parm key: key in dicts to index by example: lst = [{'id': 1, ...}, {'id': 2, ...}...] key = 'id' returns {1:{'id': 1, ...}, 2:{'id':2, ...} """ return {d[key]: dict(d, index=d[key]) for (i, d) in enumerate(seq)} class ProtectedExpatParser(expatreader.ExpatParser): """An expat parser which disables DTD's and entities by default.""" def __init__(self, forbid_dtd=True, forbid_entities=True, *args, **kwargs): # Python 2.x old style class expatreader.ExpatParser.__init__(self, *args, **kwargs) self.forbid_dtd = forbid_dtd self.forbid_entities = forbid_entities def start_doctype_decl(self, name, sysid, pubid, has_internal_subset): raise ValueError("Inline DTD forbidden") def entity_decl(self, entityName, is_parameter_entity, value, base, systemId, publicId, notationName): raise ValueError("<!ENTITY> forbidden") def unparsed_entity_decl(self, name, base, sysid, pubid, notation_name): # expat 1.2 raise ValueError("<!ENTITY> forbidden") def reset(self): expatreader.ExpatParser.reset(self) if self.forbid_dtd: self._parser.StartDoctypeDeclHandler = self.start_doctype_decl if self.forbid_entities: self._parser.EntityDeclHandler = self.entity_decl self._parser.UnparsedEntityDeclHandler = self.unparsed_entity_decl def safe_minidom_parse_string(xml_string): """Parse an XML string using minidom safely. """ try: return minidom.parseString(xml_string, parser=ProtectedExpatParser()) except sax.SAXParseException: raise expat.ExpatError() def xhtml_escape(value): """Escapes a string so it is valid within XML or XHTML.""" return saxutils.escape(value, {'"': '&quot;', "'": '&apos;'}) def get_from_path(items, path): """Returns a list of items matching the specified path. Takes an XPath-like expression e.g. prop1/prop2/prop3, and for each item in items, looks up items[prop1][prop2][prop3]. Like XPath, if any of the intermediate results are lists it will treat each list item individually. A 'None' in items or any child expressions will be ignored, this function will not throw because of None (anywhere) in items. The returned list will contain no None values. """ if path is None: raise exception.Error('Invalid mini_xpath') (first_token, sep, remainder) = path.partition('/') if first_token == '': raise exception.Error('Invalid mini_xpath') results = [] if items is None: return results if not isinstance(items, list): # Wrap single objects in a list items = [items] for item in items: if item is None: continue get_method = getattr(item, 'get', None) if get_method is None: continue child = get_method(first_token) if child is None: continue if isinstance(child, list): # Flatten intermediate lists for x in child: results.append(x) else: results.append(child) if not sep: # No more tokens return results else: return get_from_path(results, remainder) def is_valid_boolstr(val): """Check if the provided string is a valid bool string or not.""" val = str(val).lower() return (val == 'true' or val == 'false' or val == 'yes' or val == 'no' or val == 'y' or val == 'n' or val == '1' or val == '0') def is_none_string(val): """Check if a string represents a None value.""" if not isinstance(val, six.string_types): return False return val.lower() == 'none' def monkey_patch(): """Patches decorators for all functions in a specified module. If the CONF.monkey_patch set as True, this function patches a decorator for all functions in specified modules. You can set decorators for each modules using CONF.monkey_patch_modules. The format is "Module path:Decorator function". Example: 'cinder.api.ec2.cloud:' \ cinder.openstack.common.notifier.api.notify_decorator' Parameters of the decorator is as follows. (See cinder.openstack.common.notifier.api.notify_decorator) :param name: name of the function :param function: object of the function """ # If CONF.monkey_patch is not True, this function do nothing. if not CONF.monkey_patch: return # Get list of modules and decorators for module_and_decorator in CONF.monkey_patch_modules: module, decorator_name = module_and_decorator.split(':') # import decorator function decorator = importutils.import_class(decorator_name) __import__(module) # Retrieve module information using pyclbr module_data = pyclbr.readmodule_ex(module) for key in module_data.keys(): # set the decorator for the class methods if isinstance(module_data[key], pyclbr.Class): clz = importutils.import_class("%s.%s" % (module, key)) for method, func in inspect.getmembers(clz, inspect.ismethod): setattr( clz, method, decorator("%s.%s.%s" % (module, key, method), func)) # set the decorator for the function if isinstance(module_data[key], pyclbr.Function): func = importutils.import_class("%s.%s" % (module, key)) setattr(sys.modules[module], key, decorator("%s.%s" % (module, key), func)) def make_dev_path(dev, partition=None, base='/dev'):
>>> make_dev_path('xvdc') /dev/xvdc >>> make_dev_path('xvdc', 1) /dev/xvdc1 """ path = os.path.join(base, dev) if partition: path += str(partition) return path def sanitize_hostname(hostname): """Return a hostname which conforms to RFC-952 and RFC-1123 specs.""" if six.PY3: hostname = hostname.encode('latin-1', 'ignore') hostname = hostname.decode('latin-1') else: if isinstance(hostname, six.text_type): hostname = hostname.encode('latin-1', 'ignore') hostname = re.sub('[ _]', '-', hostname) hostname = re.sub('[^\w.-]+', '', hostname) hostname = hostname.lower() hostname = hostname.strip('.-') return hostname def hash_file(file_like_object): """Generate a hash for the contents of a file.""" checksum = hashlib.sha1() any(map(checksum.update, iter(lambda: file_like_object.read(32768), b''))) return checksum.hexdigest() def service_is_up(service): """Check whether a service is up based on last heartbeat.""" last_heartbeat = service['updated_at'] or service['created_at'] # Timestamps in DB are UTC. elapsed = (timeutils.utcnow(with_timezone=True) - last_heartbeat).total_seconds() return abs(elapsed) <= CONF.service_down_time def read_file_as_root(file_path): """Secure helper to read file as root.""" try: out, _err = execute('cat', file_path, run_as_root=True) return out except processutils.ProcessExecutionError: raise exception.FileNotFound(file_path=file_path) @contextlib.contextmanager def temporary_chown(path, owner_uid=None): """Temporarily chown a path. :params owner_uid: UID of temporary owner (defaults to current user) """ if owner_uid is None: owner_uid = os.getuid() orig_uid = os.stat(path).st_uid if orig_uid != owner_uid: execute('chown', owner_uid, path, run_as_root=True) try: yield finally: if orig_uid != owner_uid: execute('chown', orig_uid, path, run_as_root=True) @contextlib.contextmanager def tempdir(**kwargs): tmpdir = tempfile.mkdtemp(**kwargs) try: yield tmpdir finally: try: shutil.rmtree(tmpdir) except OSError as e: LOG.debug('Could not remove tmpdir: %s', six.text_type(e)) def walk_class_hierarchy(clazz, encountered=None): """Walk class hierarchy, yielding most derived classes first.""" if not encountered: encountered = [] for subclass in clazz.__subclasses__(): if subclass not in encountered: encountered.append(subclass) # drill down to leaves first for subsubclass in walk_class_hierarchy(subclass, encountered): yield subsubclass yield subclass def get_root_helper(): return 'sudo cinder-rootwrap %s' % CONF.rootwrap_config def brick_get_connector_properties(multipath=False, enforce_multipath=False): """Wrapper to automatically set root_helper in brick calls. :param multipath: A boolean indicating whether the connector can support multipath. :param enforce_multipath: If True, it raises exception when multipath=True is specified but multipathd is not running. If False, it falls back to multipath=False when multipathd is not running. """ root_helper = get_root_helper() return connector.get_connector_properties(root_helper, CONF.my_ip, multipath, enforce_multipath) def brick_get_connector(protocol, driver=None, execute=processutils.execute, use_multipath=False, device_scan_attempts=3, *args, **kwargs): """Wrapper to get a brick connector object. This automatically populates the required protocol as well as the root_helper needed to execute commands. """ root_helper = get_root_helper() return connector.InitiatorConnector.factory(protocol, root_helper, driver=driver, execute=execute, use_multipath=use_multipath, device_scan_attempts= device_scan_attempts, *args, **kwargs) def require_driver_initialized(driver): """Verifies if `driver` is initialized If the driver is not initialized, an exception will be raised. :params driver: The driver instance. :raises: `exception.DriverNotInitialized` """ # we can't do anything if the driver didn't init if not driver.initialized: driver_name = driver.__class__.__name__ LOG.error(_LE("Volume driver %s not initialized"), driver_name) raise exception.DriverNotInitialized() def get_file_mode(path): """This primarily exists to make unit testing easier.""" return stat.S_IMODE(os.stat(path).st_mode) def get_file_gid(path): """This primarily exists to make unit testing easier.""" return os.stat(path).st_gid def get_file_size(path): """Returns the file size.""" return os.stat(path).st_size def _get_disk_of_partition(devpath, st=None): """Gets a disk device path and status from partition path. Returns a disk device path from a partition device path, and stat for the device. If devpath is not a partition, devpath is returned as it is. For example, '/dev/sda' is returned for '/dev/sda1', and '/dev/disk1' is for '/dev/disk1p1' ('p' is prepended to the partition number if the disk name ends with numbers). """ diskpath = re.sub('(?:(?<=\d)p)?\d+$', '', devpath) if diskpath != devpath: try: st_disk = os.stat(diskpath) if stat.S_ISBLK(st_disk.st_mode): return (diskpath, st_disk) except OSError: pass # devpath is not a partition if st is None: st = os.stat(devpath) return (devpath, st) def get_bool_param(param_string, params): param = params.get(param_string, False) if not is_valid_boolstr(param): msg = _('Value %(param)s for %(param_string)s is not a ' 'boolean.') % {'param': param, 'param_string': param_string} raise exception.InvalidParameterValue(err=msg) return strutils.bool_from_string(param, strict=True) def get_blkdev_major_minor(path, lookup_for_file=True): """Get 'major:minor' number of block device. Get the device's 'major:minor' number of a block device to control I/O ratelimit of the specified path. If lookup_for_file is True and the path is a regular file, lookup a disk device which the file lies on and returns the result for the device. """ st = os.stat(path) if stat.S_ISBLK(st.st_mode): path, st = _get_disk_of_partition(path, st) return '%d:%d' % (os.major(st.st_rdev), os.minor(st.st_rdev)) elif stat.S_ISCHR(st.st_mode): # No I/O ratelimit control is provided for character devices return None elif lookup_for_file: # lookup the mounted disk which the file lies on out, _err = execute('df', path) devpath = out.split("\n")[1].split()[0] if devpath[0] is not '/': # the file is on a network file system return None return get_blkdev_major_minor(devpath, False) else: msg = _("Unable to get a block device for file \'%s\'") % path raise exception.Error(msg) def check_string_length(value, name, min_length=0, max_length=None): """Check the length of specified string. :param value: the value of the string :param name: the name of the string :param min_length: the min_length of the string :param max_length: the max_length of the string """ if not isinstance(value, six.string_types): msg = _("%s is not a string or unicode") % name raise exception.InvalidInput(message=msg) if len(value) < min_length: msg = _("%(name)s has a minimum character requirement of " "%(min_length)s.") % {'name': name, 'min_length': min_length} raise exception.InvalidInput(message=msg) if max_length and len(value) > max_length: msg = _("%(name)s has more than %(max_length)s " "characters.") % {'name': name, 'max_length': max_length} raise exception.InvalidInput(message=msg) _visible_admin_metadata_keys = ['readonly', 'attached_mode'] def add_visible_admin_metadata(volume): """Add user-visible admin metadata to regular metadata. Extracts the admin metadata keys that are to be made visible to non-administrators, and adds them to the regular metadata structure for the passed-in volume. """ visible_admin_meta = {} if volume.get('volume_admin_metadata'): if isinstance(volume['volume_admin_metadata'], dict): volume_admin_metadata = volume['volume_admin_metadata'] for key in volume_admin_metadata: if key in _visible_admin_metadata_keys: visible_admin_meta[key] = volume_admin_metadata[key] else: for item in volume['volume_admin_metadata']: if item['key'] in _visible_admin_metadata_keys: visible_admin_meta[item['key']] = item['value'] # avoid circular ref when volume is a Volume instance elif (volume.get('admin_metadata') and isinstance(volume.get('admin_metadata'), dict)): for key in _visible_admin_metadata_keys: if key in volume['admin_metadata'].keys(): visible_admin_meta[key] = volume['admin_metadata'][key] if not visible_admin_meta: return # NOTE(zhiyan): update visible administration metadata to # volume metadata, administration metadata will rewrite existing key. if volume.get('volume_metadata'): orig_meta = list(volume.get('volume_metadata')) for item in orig_meta: if item['key'] in visible_admin_meta.keys(): item['value'] = visible_admin_meta.pop(item['key']) for key, value in visible_admin_meta.items(): orig_meta.append({'key': key, 'value': value}) volume['volume_metadata'] = orig_meta # avoid circular ref when vol is a Volume instance elif (volume.get('metadata') and isinstance(volume.get('metadata'), dict)): volume['metadata'].update(visible_admin_meta) else: volume['metadata'] = visible_admin_meta def remove_invalid_filter_options(context, filters, allowed_search_options): """Remove search options that are not valid for non-admin API/context.""" if context.is_admin: # Allow all options return # Otherwise, strip out all unknown options unknown_options = [opt for opt in filters if opt not in allowed_search_options] bad_options = ", ".join(unknown_options) LOG.debug("Removing options '%s' from query.", bad_options) for opt in unknown_options: del filters[opt] def is_blk_device(dev): try: if stat.S_ISBLK(os.stat(dev).st_mode): return True return False except Exception: LOG.debug('Path %s not found in is_blk_device check', dev) return False def retry(exceptions, interval=1, retries=3, backoff_rate=2, wait_random=False): def _retry_on_exception(e): return isinstance(e, exceptions) def _backoff_sleep(previous_attempt_number, delay_since_first_attempt_ms): exp = backoff_rate ** previous_attempt_number wait_for = interval * exp if wait_random: random.seed() wait_val = random.randrange(interval * 1000.0, wait_for * 1000.0) else: wait_val = wait_for * 1000.0 LOG.debug("Sleeping for %s seconds", (wait_val / 1000.0)) return wait_val def _print_stop(previous_attempt_number, delay_since_first_attempt_ms): delay_since_first_attempt = delay_since_first_attempt_ms / 1000.0 LOG.debug("Failed attempt %s", previous_attempt_number) LOG.debug("Have been at this for %s seconds", delay_since_first_attempt) return previous_attempt_number == retries if retries < 1: raise ValueError('Retries must be greater than or ' 'equal to 1 (received: %s). ' % retries) def _decorator(f): @six.wraps(f) def _wrapper(*args, **kwargs): r = retrying.Retrying(retry_on_exception=_retry_on_exception, wait_func=_backoff_sleep, stop_func=_print_stop) return r.call(f, *args, **kwargs) return _wrapper return _decorator def convert_version_to_int(version): try: if isinstance(version, six.string_types): version = convert_version_to_tuple(version) if isinstance(version, tuple): return six.moves.reduce(lambda x, y: (x * 1000) + y, version) except Exception: msg = _("Version %s is invalid.") % version raise exception.CinderException(msg) def convert_version_to_str(version_int): version_numbers = [] factor = 1000 while version_int != 0: version_number = version_int - (version_int // factor * factor) version_numbers.insert(0, six.text_type(version_number)) version_int = version_int // factor return '.'.join(map(str, version_numbers)) def convert_version_to_tuple(version_str): return tuple(int(part) for part in version_str.split('.')) def convert_str(text): """Convert to native string. Convert bytes and Unicode strings to native strings: * convert to bytes on Python 2: encode Unicode using encodeutils.safe_encode() * convert to Unicode on Python 3: decode bytes from UTF-8 """ if six.PY2: return encodeutils.safe_encode(text) else: if isinstance(text, bytes): return text.decode('utf-8') else: return text def trace_method(f): """Decorates a function if TRACE_METHOD is true.""" @functools.wraps(f) def trace_method_logging_wrapper(*args, **kwargs): if TRACE_METHOD: return trace(f)(*args, **kwargs) return f(*args, **kwargs) return trace_method_logging_wrapper def trace_api(f): """Decorates a function if TRACE_API is true.""" @functools.wraps(f) def trace_api_logging_wrapper(*args, **kwargs): if TRACE_API: return trace(f)(*args, **kwargs) return f(*args, **kwargs) return trace_api_logging_wrapper def trace(f): """Trace calls to the decorated function. This decorator should always be defined as the outermost decorator so it is defined last. This is important so it does not interfere with other decorators. Using this decorator on a function will cause its execution to be logged at `DEBUG` level with arguments, return values, and exceptions. :returns a function decorator """ func_name = f.__name__ @functools.wraps(f) def trace_logging_wrapper(*args, **kwargs): if len(args) > 0: maybe_self = args[0] else: maybe_self = kwargs.get('self', None) if maybe_self and hasattr(maybe_self, '__module__'): logger = logging.getLogger(maybe_self.__module__) else: logger = LOG # NOTE(ameade): Don't bother going any further if DEBUG log level # is not enabled for the logger. if not logger.isEnabledFor(py_logging.DEBUG): return f(*args, **kwargs) all_args = inspect.getcallargs(f, *args, **kwargs) logger.debug('==> %(func)s: call %(all_args)r', {'func': func_name, 'all_args': all_args}) start_time = time.time() * 1000 try: result = f(*args, **kwargs) except Exception as exc: total_time = int(round(time.time() * 1000)) - start_time logger.debug('<== %(func)s: exception (%(time)dms) %(exc)r', {'func': func_name, 'time': total_time, 'exc': exc}) raise total_time = int(round(time.time() * 1000)) - start_time logger.debug('<== %(func)s: return (%(time)dms) %(result)r', {'func': func_name, 'time': total_time, 'result': result}) return result return trace_logging_wrapper class TraceWrapperMetaclass(type): """Metaclass that wraps all methods of a class with trace_method. This metaclass will cause every function inside of the class to be decorated with the trace_method decorator. To use the metaclass you define a class like so: @six.add_metaclass(utils.TraceWrapperMetaclass) class MyClass(object): """ def __new__(meta, classname, bases, classDict): newClassDict = {} for attributeName, attribute in classDict.items(): if isinstance(attribute, types.FunctionType): # replace it with a wrapped version attribute = functools.update_wrapper(trace_method(attribute), attribute) newClassDict[attributeName] = attribute return type.__new__(meta, classname, bases, newClassDict) class TraceWrapperWithABCMetaclass(abc.ABCMeta, TraceWrapperMetaclass): """Metaclass that wraps all methods of a class with trace.""" pass def setup_tracing(trace_flags): """Set global variables for each trace flag. Sets variables TRACE_METHOD and TRACE_API, which represent whether to log method and api traces. :param trace_flags: a list of strings """ global TRACE_METHOD global TRACE_API try: trace_flags = [flag.strip() for flag in trace_flags] except TypeError: # Handle when trace_flags is None or a test mock trace_flags = [] for invalid_flag in (set(trace_flags) - VALID_TRACE_FLAGS): LOG.warning(_LW('Invalid trace flag: %s'), invalid_flag) TRACE_METHOD = 'method' in trace_flags TRACE_API = 'api' in trace_flags def resolve_hostname(hostname): """Resolves host name to IP address. Resolves a host name (my.data.point.com) to an IP address (10.12.143.11). This routine also works if the data passed in hostname is already an IP. In this case, the same IP address will be returned. :param hostname: Host name to resolve. :return: IP Address for Host name. """ result = socket.getaddrinfo(hostname, None)[0] (family, socktype, proto, canonname, sockaddr) = result LOG.debug('Asked to resolve hostname %(host)s and got IP %(ip)s.', {'host': hostname, 'ip': sockaddr[0]}) return sockaddr[0]
"""Return a path to a particular device.
random_line_split
utils.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Utilities and helper functions.""" import abc import contextlib import datetime import functools import hashlib import inspect import logging as py_logging import os import pyclbr import random import re import shutil import socket import stat import sys import tempfile import time import types from xml.dom import minidom from xml.parsers import expat from xml import sax from xml.sax import expatreader from xml.sax import saxutils from os_brick.initiator import connector from oslo_concurrency import lockutils from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import log as logging from oslo_utils import encodeutils from oslo_utils import importutils from oslo_utils import strutils from oslo_utils import timeutils import retrying import six from cinder import exception from cinder.i18n import _, _LE, _LW CONF = cfg.CONF LOG = logging.getLogger(__name__) ISO_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S" PERFECT_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f" VALID_TRACE_FLAGS = {'method', 'api'} TRACE_METHOD = False TRACE_API = False synchronized = lockutils.synchronized_with_prefix('cinder-') def find_config(config_path): """Find a configuration file using the given hint. :param config_path: Full or relative path to the config. :returns: Full path of the config, if it exists. :raises: `cinder.exception.ConfigNotFound` """ possible_locations = [ config_path, os.path.join(CONF.state_path, "etc", "cinder", config_path), os.path.join(CONF.state_path, "etc", config_path), os.path.join(CONF.state_path, config_path), "/etc/cinder/%s" % config_path, ] for path in possible_locations: if os.path.exists(path): return os.path.abspath(path) raise exception.ConfigNotFound(path=os.path.abspath(config_path)) def as_int(obj, quiet=True): # Try "2" -> 2
def is_int_like(val): """Check if a value looks like an int.""" try: return str(int(val)) == str(val) except Exception: return False def check_exclusive_options(**kwargs): """Checks that only one of the provided options is actually not-none. Iterates over all the kwargs passed in and checks that only one of said arguments is not-none, if more than one is not-none then an exception will be raised with the names of those arguments who were not-none. """ if not kwargs: return pretty_keys = kwargs.pop("pretty_keys", True) exclusive_options = {} for (k, v) in kwargs.items(): if v is not None: exclusive_options[k] = True if len(exclusive_options) > 1: # Change the format of the names from pythonic to # something that is more readable. # # Ex: 'the_key' -> 'the key' if pretty_keys: names = [k.replace('_', ' ') for k in kwargs.keys()] else: names = kwargs.keys() names = ", ".join(sorted(names)) msg = (_("May specify only one of %s") % (names)) raise exception.InvalidInput(reason=msg) def execute(*cmd, **kwargs): """Convenience wrapper around oslo's execute() method.""" if 'run_as_root' in kwargs and 'root_helper' not in kwargs: kwargs['root_helper'] = get_root_helper() return processutils.execute(*cmd, **kwargs) def check_ssh_injection(cmd_list): ssh_injection_pattern = ['`', '$', '|', '||', ';', '&', '&&', '>', '>>', '<'] # Check whether injection attacks exist for arg in cmd_list: arg = arg.strip() # Check for matching quotes on the ends is_quoted = re.match('^(?P<quote>[\'"])(?P<quoted>.*)(?P=quote)$', arg) if is_quoted: # Check for unescaped quotes within the quoted argument quoted = is_quoted.group('quoted') if quoted: if (re.match('[\'"]', quoted) or re.search('[^\\\\][\'"]', quoted)): raise exception.SSHInjectionThreat(command=cmd_list) else: # We only allow spaces within quoted arguments, and that # is the only special character allowed within quotes if len(arg.split()) > 1: raise exception.SSHInjectionThreat(command=cmd_list) # Second, check whether danger character in command. So the shell # special operator must be a single argument. for c in ssh_injection_pattern: if c not in arg: continue result = arg.find(c) if not result == -1: if result == 0 or not arg[result - 1] == '\\': raise exception.SSHInjectionThreat(command=cmd_list) def create_channel(client, width, height): """Invoke an interactive shell session on server.""" channel = client.invoke_shell() channel.resize_pty(width, height) return channel def cinderdir(): import cinder return os.path.abspath(cinder.__file__).split('cinder/__init__.py')[0] def last_completed_audit_period(unit=None): """This method gives you the most recently *completed* audit period. arguments: units: string, one of 'hour', 'day', 'month', 'year' Periods normally begin at the beginning (UTC) of the period unit (So a 'day' period begins at midnight UTC, a 'month' unit on the 1st, a 'year' on Jan, 1) unit string may be appended with an optional offset like so: 'day@18' This will begin the period at 18:00 UTC. 'month@15' starts a monthly period on the 15th, and year@3 begins a yearly one on March 1st. returns: 2 tuple of datetimes (begin, end) The begin timestamp of this audit period is the same as the end of the previous. """ if not unit: unit = CONF.volume_usage_audit_period offset = 0 if '@' in unit: unit, offset = unit.split("@", 1) offset = int(offset) rightnow = timeutils.utcnow() if unit not in ('month', 'day', 'year', 'hour'): raise ValueError('Time period must be hour, day, month or year') if unit == 'month': if offset == 0: offset = 1 end = datetime.datetime(day=offset, month=rightnow.month, year=rightnow.year) if end >= rightnow: year = rightnow.year if 1 >= rightnow.month: year -= 1 month = 12 + (rightnow.month - 1) else: month = rightnow.month - 1 end = datetime.datetime(day=offset, month=month, year=year) year = end.year if 1 >= end.month: year -= 1 month = 12 + (end.month - 1) else: month = end.month - 1 begin = datetime.datetime(day=offset, month=month, year=year) elif unit == 'year': if offset == 0: offset = 1 end = datetime.datetime(day=1, month=offset, year=rightnow.year) if end >= rightnow: end = datetime.datetime(day=1, month=offset, year=rightnow.year - 1) begin = datetime.datetime(day=1, month=offset, year=rightnow.year - 2) else: begin = datetime.datetime(day=1, month=offset, year=rightnow.year - 1) elif unit == 'day': end = datetime.datetime(hour=offset, day=rightnow.day, month=rightnow.month, year=rightnow.year) if end >= rightnow: end = end - datetime.timedelta(days=1) begin = end - datetime.timedelta(days=1) elif unit == 'hour': end = rightnow.replace(minute=offset, second=0, microsecond=0) if end >= rightnow: end = end - datetime.timedelta(hours=1) begin = end - datetime.timedelta(hours=1) return (begin, end) def list_of_dicts_to_dict(seq, key): """Convert list of dicts to a indexted dict. Takes a list of dicts, and converts it a nested dict indexed by <key> :param seq: list of dicts :parm key: key in dicts to index by example: lst = [{'id': 1, ...}, {'id': 2, ...}...] key = 'id' returns {1:{'id': 1, ...}, 2:{'id':2, ...} """ return {d[key]: dict(d, index=d[key]) for (i, d) in enumerate(seq)} class ProtectedExpatParser(expatreader.ExpatParser): """An expat parser which disables DTD's and entities by default.""" def __init__(self, forbid_dtd=True, forbid_entities=True, *args, **kwargs): # Python 2.x old style class expatreader.ExpatParser.__init__(self, *args, **kwargs) self.forbid_dtd = forbid_dtd self.forbid_entities = forbid_entities def start_doctype_decl(self, name, sysid, pubid, has_internal_subset): raise ValueError("Inline DTD forbidden") def entity_decl(self, entityName, is_parameter_entity, value, base, systemId, publicId, notationName): raise ValueError("<!ENTITY> forbidden") def unparsed_entity_decl(self, name, base, sysid, pubid, notation_name): # expat 1.2 raise ValueError("<!ENTITY> forbidden") def reset(self): expatreader.ExpatParser.reset(self) if self.forbid_dtd: self._parser.StartDoctypeDeclHandler = self.start_doctype_decl if self.forbid_entities: self._parser.EntityDeclHandler = self.entity_decl self._parser.UnparsedEntityDeclHandler = self.unparsed_entity_decl def safe_minidom_parse_string(xml_string): """Parse an XML string using minidom safely. """ try: return minidom.parseString(xml_string, parser=ProtectedExpatParser()) except sax.SAXParseException: raise expat.ExpatError() def xhtml_escape(value): """Escapes a string so it is valid within XML or XHTML.""" return saxutils.escape(value, {'"': '&quot;', "'": '&apos;'}) def get_from_path(items, path): """Returns a list of items matching the specified path. Takes an XPath-like expression e.g. prop1/prop2/prop3, and for each item in items, looks up items[prop1][prop2][prop3]. Like XPath, if any of the intermediate results are lists it will treat each list item individually. A 'None' in items or any child expressions will be ignored, this function will not throw because of None (anywhere) in items. The returned list will contain no None values. """ if path is None: raise exception.Error('Invalid mini_xpath') (first_token, sep, remainder) = path.partition('/') if first_token == '': raise exception.Error('Invalid mini_xpath') results = [] if items is None: return results if not isinstance(items, list): # Wrap single objects in a list items = [items] for item in items: if item is None: continue get_method = getattr(item, 'get', None) if get_method is None: continue child = get_method(first_token) if child is None: continue if isinstance(child, list): # Flatten intermediate lists for x in child: results.append(x) else: results.append(child) if not sep: # No more tokens return results else: return get_from_path(results, remainder) def is_valid_boolstr(val): """Check if the provided string is a valid bool string or not.""" val = str(val).lower() return (val == 'true' or val == 'false' or val == 'yes' or val == 'no' or val == 'y' or val == 'n' or val == '1' or val == '0') def is_none_string(val): """Check if a string represents a None value.""" if not isinstance(val, six.string_types): return False return val.lower() == 'none' def monkey_patch(): """Patches decorators for all functions in a specified module. If the CONF.monkey_patch set as True, this function patches a decorator for all functions in specified modules. You can set decorators for each modules using CONF.monkey_patch_modules. The format is "Module path:Decorator function". Example: 'cinder.api.ec2.cloud:' \ cinder.openstack.common.notifier.api.notify_decorator' Parameters of the decorator is as follows. (See cinder.openstack.common.notifier.api.notify_decorator) :param name: name of the function :param function: object of the function """ # If CONF.monkey_patch is not True, this function do nothing. if not CONF.monkey_patch: return # Get list of modules and decorators for module_and_decorator in CONF.monkey_patch_modules: module, decorator_name = module_and_decorator.split(':') # import decorator function decorator = importutils.import_class(decorator_name) __import__(module) # Retrieve module information using pyclbr module_data = pyclbr.readmodule_ex(module) for key in module_data.keys(): # set the decorator for the class methods if isinstance(module_data[key], pyclbr.Class): clz = importutils.import_class("%s.%s" % (module, key)) for method, func in inspect.getmembers(clz, inspect.ismethod): setattr( clz, method, decorator("%s.%s.%s" % (module, key, method), func)) # set the decorator for the function if isinstance(module_data[key], pyclbr.Function): func = importutils.import_class("%s.%s" % (module, key)) setattr(sys.modules[module], key, decorator("%s.%s" % (module, key), func)) def make_dev_path(dev, partition=None, base='/dev'): """Return a path to a particular device. >>> make_dev_path('xvdc') /dev/xvdc >>> make_dev_path('xvdc', 1) /dev/xvdc1 """ path = os.path.join(base, dev) if partition: path += str(partition) return path def sanitize_hostname(hostname): """Return a hostname which conforms to RFC-952 and RFC-1123 specs.""" if six.PY3: hostname = hostname.encode('latin-1', 'ignore') hostname = hostname.decode('latin-1') else: if isinstance(hostname, six.text_type): hostname = hostname.encode('latin-1', 'ignore') hostname = re.sub('[ _]', '-', hostname) hostname = re.sub('[^\w.-]+', '', hostname) hostname = hostname.lower() hostname = hostname.strip('.-') return hostname def hash_file(file_like_object): """Generate a hash for the contents of a file.""" checksum = hashlib.sha1() any(map(checksum.update, iter(lambda: file_like_object.read(32768), b''))) return checksum.hexdigest() def service_is_up(service): """Check whether a service is up based on last heartbeat.""" last_heartbeat = service['updated_at'] or service['created_at'] # Timestamps in DB are UTC. elapsed = (timeutils.utcnow(with_timezone=True) - last_heartbeat).total_seconds() return abs(elapsed) <= CONF.service_down_time def read_file_as_root(file_path): """Secure helper to read file as root.""" try: out, _err = execute('cat', file_path, run_as_root=True) return out except processutils.ProcessExecutionError: raise exception.FileNotFound(file_path=file_path) @contextlib.contextmanager def temporary_chown(path, owner_uid=None): """Temporarily chown a path. :params owner_uid: UID of temporary owner (defaults to current user) """ if owner_uid is None: owner_uid = os.getuid() orig_uid = os.stat(path).st_uid if orig_uid != owner_uid: execute('chown', owner_uid, path, run_as_root=True) try: yield finally: if orig_uid != owner_uid: execute('chown', orig_uid, path, run_as_root=True) @contextlib.contextmanager def tempdir(**kwargs): tmpdir = tempfile.mkdtemp(**kwargs) try: yield tmpdir finally: try: shutil.rmtree(tmpdir) except OSError as e: LOG.debug('Could not remove tmpdir: %s', six.text_type(e)) def walk_class_hierarchy(clazz, encountered=None): """Walk class hierarchy, yielding most derived classes first.""" if not encountered: encountered = [] for subclass in clazz.__subclasses__(): if subclass not in encountered: encountered.append(subclass) # drill down to leaves first for subsubclass in walk_class_hierarchy(subclass, encountered): yield subsubclass yield subclass def get_root_helper(): return 'sudo cinder-rootwrap %s' % CONF.rootwrap_config def brick_get_connector_properties(multipath=False, enforce_multipath=False): """Wrapper to automatically set root_helper in brick calls. :param multipath: A boolean indicating whether the connector can support multipath. :param enforce_multipath: If True, it raises exception when multipath=True is specified but multipathd is not running. If False, it falls back to multipath=False when multipathd is not running. """ root_helper = get_root_helper() return connector.get_connector_properties(root_helper, CONF.my_ip, multipath, enforce_multipath) def brick_get_connector(protocol, driver=None, execute=processutils.execute, use_multipath=False, device_scan_attempts=3, *args, **kwargs): """Wrapper to get a brick connector object. This automatically populates the required protocol as well as the root_helper needed to execute commands. """ root_helper = get_root_helper() return connector.InitiatorConnector.factory(protocol, root_helper, driver=driver, execute=execute, use_multipath=use_multipath, device_scan_attempts= device_scan_attempts, *args, **kwargs) def require_driver_initialized(driver): """Verifies if `driver` is initialized If the driver is not initialized, an exception will be raised. :params driver: The driver instance. :raises: `exception.DriverNotInitialized` """ # we can't do anything if the driver didn't init if not driver.initialized: driver_name = driver.__class__.__name__ LOG.error(_LE("Volume driver %s not initialized"), driver_name) raise exception.DriverNotInitialized() def get_file_mode(path): """This primarily exists to make unit testing easier.""" return stat.S_IMODE(os.stat(path).st_mode) def get_file_gid(path): """This primarily exists to make unit testing easier.""" return os.stat(path).st_gid def get_file_size(path): """Returns the file size.""" return os.stat(path).st_size def _get_disk_of_partition(devpath, st=None): """Gets a disk device path and status from partition path. Returns a disk device path from a partition device path, and stat for the device. If devpath is not a partition, devpath is returned as it is. For example, '/dev/sda' is returned for '/dev/sda1', and '/dev/disk1' is for '/dev/disk1p1' ('p' is prepended to the partition number if the disk name ends with numbers). """ diskpath = re.sub('(?:(?<=\d)p)?\d+$', '', devpath) if diskpath != devpath: try: st_disk = os.stat(diskpath) if stat.S_ISBLK(st_disk.st_mode): return (diskpath, st_disk) except OSError: pass # devpath is not a partition if st is None: st = os.stat(devpath) return (devpath, st) def get_bool_param(param_string, params): param = params.get(param_string, False) if not is_valid_boolstr(param): msg = _('Value %(param)s for %(param_string)s is not a ' 'boolean.') % {'param': param, 'param_string': param_string} raise exception.InvalidParameterValue(err=msg) return strutils.bool_from_string(param, strict=True) def get_blkdev_major_minor(path, lookup_for_file=True): """Get 'major:minor' number of block device. Get the device's 'major:minor' number of a block device to control I/O ratelimit of the specified path. If lookup_for_file is True and the path is a regular file, lookup a disk device which the file lies on and returns the result for the device. """ st = os.stat(path) if stat.S_ISBLK(st.st_mode): path, st = _get_disk_of_partition(path, st) return '%d:%d' % (os.major(st.st_rdev), os.minor(st.st_rdev)) elif stat.S_ISCHR(st.st_mode): # No I/O ratelimit control is provided for character devices return None elif lookup_for_file: # lookup the mounted disk which the file lies on out, _err = execute('df', path) devpath = out.split("\n")[1].split()[0] if devpath[0] is not '/': # the file is on a network file system return None return get_blkdev_major_minor(devpath, False) else: msg = _("Unable to get a block device for file \'%s\'") % path raise exception.Error(msg) def check_string_length(value, name, min_length=0, max_length=None): """Check the length of specified string. :param value: the value of the string :param name: the name of the string :param min_length: the min_length of the string :param max_length: the max_length of the string """ if not isinstance(value, six.string_types): msg = _("%s is not a string or unicode") % name raise exception.InvalidInput(message=msg) if len(value) < min_length: msg = _("%(name)s has a minimum character requirement of " "%(min_length)s.") % {'name': name, 'min_length': min_length} raise exception.InvalidInput(message=msg) if max_length and len(value) > max_length: msg = _("%(name)s has more than %(max_length)s " "characters.") % {'name': name, 'max_length': max_length} raise exception.InvalidInput(message=msg) _visible_admin_metadata_keys = ['readonly', 'attached_mode'] def add_visible_admin_metadata(volume): """Add user-visible admin metadata to regular metadata. Extracts the admin metadata keys that are to be made visible to non-administrators, and adds them to the regular metadata structure for the passed-in volume. """ visible_admin_meta = {} if volume.get('volume_admin_metadata'): if isinstance(volume['volume_admin_metadata'], dict): volume_admin_metadata = volume['volume_admin_metadata'] for key in volume_admin_metadata: if key in _visible_admin_metadata_keys: visible_admin_meta[key] = volume_admin_metadata[key] else: for item in volume['volume_admin_metadata']: if item['key'] in _visible_admin_metadata_keys: visible_admin_meta[item['key']] = item['value'] # avoid circular ref when volume is a Volume instance elif (volume.get('admin_metadata') and isinstance(volume.get('admin_metadata'), dict)): for key in _visible_admin_metadata_keys: if key in volume['admin_metadata'].keys(): visible_admin_meta[key] = volume['admin_metadata'][key] if not visible_admin_meta: return # NOTE(zhiyan): update visible administration metadata to # volume metadata, administration metadata will rewrite existing key. if volume.get('volume_metadata'): orig_meta = list(volume.get('volume_metadata')) for item in orig_meta: if item['key'] in visible_admin_meta.keys(): item['value'] = visible_admin_meta.pop(item['key']) for key, value in visible_admin_meta.items(): orig_meta.append({'key': key, 'value': value}) volume['volume_metadata'] = orig_meta # avoid circular ref when vol is a Volume instance elif (volume.get('metadata') and isinstance(volume.get('metadata'), dict)): volume['metadata'].update(visible_admin_meta) else: volume['metadata'] = visible_admin_meta def remove_invalid_filter_options(context, filters, allowed_search_options): """Remove search options that are not valid for non-admin API/context.""" if context.is_admin: # Allow all options return # Otherwise, strip out all unknown options unknown_options = [opt for opt in filters if opt not in allowed_search_options] bad_options = ", ".join(unknown_options) LOG.debug("Removing options '%s' from query.", bad_options) for opt in unknown_options: del filters[opt] def is_blk_device(dev): try: if stat.S_ISBLK(os.stat(dev).st_mode): return True return False except Exception: LOG.debug('Path %s not found in is_blk_device check', dev) return False def retry(exceptions, interval=1, retries=3, backoff_rate=2, wait_random=False): def _retry_on_exception(e): return isinstance(e, exceptions) def _backoff_sleep(previous_attempt_number, delay_since_first_attempt_ms): exp = backoff_rate ** previous_attempt_number wait_for = interval * exp if wait_random: random.seed() wait_val = random.randrange(interval * 1000.0, wait_for * 1000.0) else: wait_val = wait_for * 1000.0 LOG.debug("Sleeping for %s seconds", (wait_val / 1000.0)) return wait_val def _print_stop(previous_attempt_number, delay_since_first_attempt_ms): delay_since_first_attempt = delay_since_first_attempt_ms / 1000.0 LOG.debug("Failed attempt %s", previous_attempt_number) LOG.debug("Have been at this for %s seconds", delay_since_first_attempt) return previous_attempt_number == retries if retries < 1: raise ValueError('Retries must be greater than or ' 'equal to 1 (received: %s). ' % retries) def _decorator(f): @six.wraps(f) def _wrapper(*args, **kwargs): r = retrying.Retrying(retry_on_exception=_retry_on_exception, wait_func=_backoff_sleep, stop_func=_print_stop) return r.call(f, *args, **kwargs) return _wrapper return _decorator def convert_version_to_int(version): try: if isinstance(version, six.string_types): version = convert_version_to_tuple(version) if isinstance(version, tuple): return six.moves.reduce(lambda x, y: (x * 1000) + y, version) except Exception: msg = _("Version %s is invalid.") % version raise exception.CinderException(msg) def convert_version_to_str(version_int): version_numbers = [] factor = 1000 while version_int != 0: version_number = version_int - (version_int // factor * factor) version_numbers.insert(0, six.text_type(version_number)) version_int = version_int // factor return '.'.join(map(str, version_numbers)) def convert_version_to_tuple(version_str): return tuple(int(part) for part in version_str.split('.')) def convert_str(text): """Convert to native string. Convert bytes and Unicode strings to native strings: * convert to bytes on Python 2: encode Unicode using encodeutils.safe_encode() * convert to Unicode on Python 3: decode bytes from UTF-8 """ if six.PY2: return encodeutils.safe_encode(text) else: if isinstance(text, bytes): return text.decode('utf-8') else: return text def trace_method(f): """Decorates a function if TRACE_METHOD is true.""" @functools.wraps(f) def trace_method_logging_wrapper(*args, **kwargs): if TRACE_METHOD: return trace(f)(*args, **kwargs) return f(*args, **kwargs) return trace_method_logging_wrapper def trace_api(f): """Decorates a function if TRACE_API is true.""" @functools.wraps(f) def trace_api_logging_wrapper(*args, **kwargs): if TRACE_API: return trace(f)(*args, **kwargs) return f(*args, **kwargs) return trace_api_logging_wrapper def trace(f): """Trace calls to the decorated function. This decorator should always be defined as the outermost decorator so it is defined last. This is important so it does not interfere with other decorators. Using this decorator on a function will cause its execution to be logged at `DEBUG` level with arguments, return values, and exceptions. :returns a function decorator """ func_name = f.__name__ @functools.wraps(f) def trace_logging_wrapper(*args, **kwargs): if len(args) > 0: maybe_self = args[0] else: maybe_self = kwargs.get('self', None) if maybe_self and hasattr(maybe_self, '__module__'): logger = logging.getLogger(maybe_self.__module__) else: logger = LOG # NOTE(ameade): Don't bother going any further if DEBUG log level # is not enabled for the logger. if not logger.isEnabledFor(py_logging.DEBUG): return f(*args, **kwargs) all_args = inspect.getcallargs(f, *args, **kwargs) logger.debug('==> %(func)s: call %(all_args)r', {'func': func_name, 'all_args': all_args}) start_time = time.time() * 1000 try: result = f(*args, **kwargs) except Exception as exc: total_time = int(round(time.time() * 1000)) - start_time logger.debug('<== %(func)s: exception (%(time)dms) %(exc)r', {'func': func_name, 'time': total_time, 'exc': exc}) raise total_time = int(round(time.time() * 1000)) - start_time logger.debug('<== %(func)s: return (%(time)dms) %(result)r', {'func': func_name, 'time': total_time, 'result': result}) return result return trace_logging_wrapper class TraceWrapperMetaclass(type): """Metaclass that wraps all methods of a class with trace_method. This metaclass will cause every function inside of the class to be decorated with the trace_method decorator. To use the metaclass you define a class like so: @six.add_metaclass(utils.TraceWrapperMetaclass) class MyClass(object): """ def __new__(meta, classname, bases, classDict): newClassDict = {} for attributeName, attribute in classDict.items(): if isinstance(attribute, types.FunctionType): # replace it with a wrapped version attribute = functools.update_wrapper(trace_method(attribute), attribute) newClassDict[attributeName] = attribute return type.__new__(meta, classname, bases, newClassDict) class TraceWrapperWithABCMetaclass(abc.ABCMeta, TraceWrapperMetaclass): """Metaclass that wraps all methods of a class with trace.""" pass def setup_tracing(trace_flags): """Set global variables for each trace flag. Sets variables TRACE_METHOD and TRACE_API, which represent whether to log method and api traces. :param trace_flags: a list of strings """ global TRACE_METHOD global TRACE_API try: trace_flags = [flag.strip() for flag in trace_flags] except TypeError: # Handle when trace_flags is None or a test mock trace_flags = [] for invalid_flag in (set(trace_flags) - VALID_TRACE_FLAGS): LOG.warning(_LW('Invalid trace flag: %s'), invalid_flag) TRACE_METHOD = 'method' in trace_flags TRACE_API = 'api' in trace_flags def resolve_hostname(hostname): """Resolves host name to IP address. Resolves a host name (my.data.point.com) to an IP address (10.12.143.11). This routine also works if the data passed in hostname is already an IP. In this case, the same IP address will be returned. :param hostname: Host name to resolve. :return: IP Address for Host name. """ result = socket.getaddrinfo(hostname, None)[0] (family, socktype, proto, canonname, sockaddr) = result LOG.debug('Asked to resolve hostname %(host)s and got IP %(ip)s.', {'host': hostname, 'ip': sockaddr[0]}) return sockaddr[0]
try: return int(obj) except (ValueError, TypeError): pass # Try "2.5" -> 2 try: return int(float(obj)) except (ValueError, TypeError): pass # Eck, not sure what this is then. if not quiet: raise TypeError(_("Can not translate %s to integer.") % (obj)) return obj
identifier_body
utils.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Utilities and helper functions.""" import abc import contextlib import datetime import functools import hashlib import inspect import logging as py_logging import os import pyclbr import random import re import shutil import socket import stat import sys import tempfile import time import types from xml.dom import minidom from xml.parsers import expat from xml import sax from xml.sax import expatreader from xml.sax import saxutils from os_brick.initiator import connector from oslo_concurrency import lockutils from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import log as logging from oslo_utils import encodeutils from oslo_utils import importutils from oslo_utils import strutils from oslo_utils import timeutils import retrying import six from cinder import exception from cinder.i18n import _, _LE, _LW CONF = cfg.CONF LOG = logging.getLogger(__name__) ISO_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S" PERFECT_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f" VALID_TRACE_FLAGS = {'method', 'api'} TRACE_METHOD = False TRACE_API = False synchronized = lockutils.synchronized_with_prefix('cinder-') def find_config(config_path): """Find a configuration file using the given hint. :param config_path: Full or relative path to the config. :returns: Full path of the config, if it exists. :raises: `cinder.exception.ConfigNotFound` """ possible_locations = [ config_path, os.path.join(CONF.state_path, "etc", "cinder", config_path), os.path.join(CONF.state_path, "etc", config_path), os.path.join(CONF.state_path, config_path), "/etc/cinder/%s" % config_path, ] for path in possible_locations: if os.path.exists(path): return os.path.abspath(path) raise exception.ConfigNotFound(path=os.path.abspath(config_path)) def as_int(obj, quiet=True): # Try "2" -> 2 try: return int(obj) except (ValueError, TypeError): pass # Try "2.5" -> 2 try: return int(float(obj)) except (ValueError, TypeError): pass # Eck, not sure what this is then. if not quiet: raise TypeError(_("Can not translate %s to integer.") % (obj)) return obj def is_int_like(val): """Check if a value looks like an int.""" try: return str(int(val)) == str(val) except Exception: return False def check_exclusive_options(**kwargs): """Checks that only one of the provided options is actually not-none. Iterates over all the kwargs passed in and checks that only one of said arguments is not-none, if more than one is not-none then an exception will be raised with the names of those arguments who were not-none. """ if not kwargs: return pretty_keys = kwargs.pop("pretty_keys", True) exclusive_options = {} for (k, v) in kwargs.items(): if v is not None: exclusive_options[k] = True if len(exclusive_options) > 1: # Change the format of the names from pythonic to # something that is more readable. # # Ex: 'the_key' -> 'the key' if pretty_keys: names = [k.replace('_', ' ') for k in kwargs.keys()] else: names = kwargs.keys() names = ", ".join(sorted(names)) msg = (_("May specify only one of %s") % (names)) raise exception.InvalidInput(reason=msg) def
(*cmd, **kwargs): """Convenience wrapper around oslo's execute() method.""" if 'run_as_root' in kwargs and 'root_helper' not in kwargs: kwargs['root_helper'] = get_root_helper() return processutils.execute(*cmd, **kwargs) def check_ssh_injection(cmd_list): ssh_injection_pattern = ['`', '$', '|', '||', ';', '&', '&&', '>', '>>', '<'] # Check whether injection attacks exist for arg in cmd_list: arg = arg.strip() # Check for matching quotes on the ends is_quoted = re.match('^(?P<quote>[\'"])(?P<quoted>.*)(?P=quote)$', arg) if is_quoted: # Check for unescaped quotes within the quoted argument quoted = is_quoted.group('quoted') if quoted: if (re.match('[\'"]', quoted) or re.search('[^\\\\][\'"]', quoted)): raise exception.SSHInjectionThreat(command=cmd_list) else: # We only allow spaces within quoted arguments, and that # is the only special character allowed within quotes if len(arg.split()) > 1: raise exception.SSHInjectionThreat(command=cmd_list) # Second, check whether danger character in command. So the shell # special operator must be a single argument. for c in ssh_injection_pattern: if c not in arg: continue result = arg.find(c) if not result == -1: if result == 0 or not arg[result - 1] == '\\': raise exception.SSHInjectionThreat(command=cmd_list) def create_channel(client, width, height): """Invoke an interactive shell session on server.""" channel = client.invoke_shell() channel.resize_pty(width, height) return channel def cinderdir(): import cinder return os.path.abspath(cinder.__file__).split('cinder/__init__.py')[0] def last_completed_audit_period(unit=None): """This method gives you the most recently *completed* audit period. arguments: units: string, one of 'hour', 'day', 'month', 'year' Periods normally begin at the beginning (UTC) of the period unit (So a 'day' period begins at midnight UTC, a 'month' unit on the 1st, a 'year' on Jan, 1) unit string may be appended with an optional offset like so: 'day@18' This will begin the period at 18:00 UTC. 'month@15' starts a monthly period on the 15th, and year@3 begins a yearly one on March 1st. returns: 2 tuple of datetimes (begin, end) The begin timestamp of this audit period is the same as the end of the previous. """ if not unit: unit = CONF.volume_usage_audit_period offset = 0 if '@' in unit: unit, offset = unit.split("@", 1) offset = int(offset) rightnow = timeutils.utcnow() if unit not in ('month', 'day', 'year', 'hour'): raise ValueError('Time period must be hour, day, month or year') if unit == 'month': if offset == 0: offset = 1 end = datetime.datetime(day=offset, month=rightnow.month, year=rightnow.year) if end >= rightnow: year = rightnow.year if 1 >= rightnow.month: year -= 1 month = 12 + (rightnow.month - 1) else: month = rightnow.month - 1 end = datetime.datetime(day=offset, month=month, year=year) year = end.year if 1 >= end.month: year -= 1 month = 12 + (end.month - 1) else: month = end.month - 1 begin = datetime.datetime(day=offset, month=month, year=year) elif unit == 'year': if offset == 0: offset = 1 end = datetime.datetime(day=1, month=offset, year=rightnow.year) if end >= rightnow: end = datetime.datetime(day=1, month=offset, year=rightnow.year - 1) begin = datetime.datetime(day=1, month=offset, year=rightnow.year - 2) else: begin = datetime.datetime(day=1, month=offset, year=rightnow.year - 1) elif unit == 'day': end = datetime.datetime(hour=offset, day=rightnow.day, month=rightnow.month, year=rightnow.year) if end >= rightnow: end = end - datetime.timedelta(days=1) begin = end - datetime.timedelta(days=1) elif unit == 'hour': end = rightnow.replace(minute=offset, second=0, microsecond=0) if end >= rightnow: end = end - datetime.timedelta(hours=1) begin = end - datetime.timedelta(hours=1) return (begin, end) def list_of_dicts_to_dict(seq, key): """Convert list of dicts to a indexted dict. Takes a list of dicts, and converts it a nested dict indexed by <key> :param seq: list of dicts :parm key: key in dicts to index by example: lst = [{'id': 1, ...}, {'id': 2, ...}...] key = 'id' returns {1:{'id': 1, ...}, 2:{'id':2, ...} """ return {d[key]: dict(d, index=d[key]) for (i, d) in enumerate(seq)} class ProtectedExpatParser(expatreader.ExpatParser): """An expat parser which disables DTD's and entities by default.""" def __init__(self, forbid_dtd=True, forbid_entities=True, *args, **kwargs): # Python 2.x old style class expatreader.ExpatParser.__init__(self, *args, **kwargs) self.forbid_dtd = forbid_dtd self.forbid_entities = forbid_entities def start_doctype_decl(self, name, sysid, pubid, has_internal_subset): raise ValueError("Inline DTD forbidden") def entity_decl(self, entityName, is_parameter_entity, value, base, systemId, publicId, notationName): raise ValueError("<!ENTITY> forbidden") def unparsed_entity_decl(self, name, base, sysid, pubid, notation_name): # expat 1.2 raise ValueError("<!ENTITY> forbidden") def reset(self): expatreader.ExpatParser.reset(self) if self.forbid_dtd: self._parser.StartDoctypeDeclHandler = self.start_doctype_decl if self.forbid_entities: self._parser.EntityDeclHandler = self.entity_decl self._parser.UnparsedEntityDeclHandler = self.unparsed_entity_decl def safe_minidom_parse_string(xml_string): """Parse an XML string using minidom safely. """ try: return minidom.parseString(xml_string, parser=ProtectedExpatParser()) except sax.SAXParseException: raise expat.ExpatError() def xhtml_escape(value): """Escapes a string so it is valid within XML or XHTML.""" return saxutils.escape(value, {'"': '&quot;', "'": '&apos;'}) def get_from_path(items, path): """Returns a list of items matching the specified path. Takes an XPath-like expression e.g. prop1/prop2/prop3, and for each item in items, looks up items[prop1][prop2][prop3]. Like XPath, if any of the intermediate results are lists it will treat each list item individually. A 'None' in items or any child expressions will be ignored, this function will not throw because of None (anywhere) in items. The returned list will contain no None values. """ if path is None: raise exception.Error('Invalid mini_xpath') (first_token, sep, remainder) = path.partition('/') if first_token == '': raise exception.Error('Invalid mini_xpath') results = [] if items is None: return results if not isinstance(items, list): # Wrap single objects in a list items = [items] for item in items: if item is None: continue get_method = getattr(item, 'get', None) if get_method is None: continue child = get_method(first_token) if child is None: continue if isinstance(child, list): # Flatten intermediate lists for x in child: results.append(x) else: results.append(child) if not sep: # No more tokens return results else: return get_from_path(results, remainder) def is_valid_boolstr(val): """Check if the provided string is a valid bool string or not.""" val = str(val).lower() return (val == 'true' or val == 'false' or val == 'yes' or val == 'no' or val == 'y' or val == 'n' or val == '1' or val == '0') def is_none_string(val): """Check if a string represents a None value.""" if not isinstance(val, six.string_types): return False return val.lower() == 'none' def monkey_patch(): """Patches decorators for all functions in a specified module. If the CONF.monkey_patch set as True, this function patches a decorator for all functions in specified modules. You can set decorators for each modules using CONF.monkey_patch_modules. The format is "Module path:Decorator function". Example: 'cinder.api.ec2.cloud:' \ cinder.openstack.common.notifier.api.notify_decorator' Parameters of the decorator is as follows. (See cinder.openstack.common.notifier.api.notify_decorator) :param name: name of the function :param function: object of the function """ # If CONF.monkey_patch is not True, this function do nothing. if not CONF.monkey_patch: return # Get list of modules and decorators for module_and_decorator in CONF.monkey_patch_modules: module, decorator_name = module_and_decorator.split(':') # import decorator function decorator = importutils.import_class(decorator_name) __import__(module) # Retrieve module information using pyclbr module_data = pyclbr.readmodule_ex(module) for key in module_data.keys(): # set the decorator for the class methods if isinstance(module_data[key], pyclbr.Class): clz = importutils.import_class("%s.%s" % (module, key)) for method, func in inspect.getmembers(clz, inspect.ismethod): setattr( clz, method, decorator("%s.%s.%s" % (module, key, method), func)) # set the decorator for the function if isinstance(module_data[key], pyclbr.Function): func = importutils.import_class("%s.%s" % (module, key)) setattr(sys.modules[module], key, decorator("%s.%s" % (module, key), func)) def make_dev_path(dev, partition=None, base='/dev'): """Return a path to a particular device. >>> make_dev_path('xvdc') /dev/xvdc >>> make_dev_path('xvdc', 1) /dev/xvdc1 """ path = os.path.join(base, dev) if partition: path += str(partition) return path def sanitize_hostname(hostname): """Return a hostname which conforms to RFC-952 and RFC-1123 specs.""" if six.PY3: hostname = hostname.encode('latin-1', 'ignore') hostname = hostname.decode('latin-1') else: if isinstance(hostname, six.text_type): hostname = hostname.encode('latin-1', 'ignore') hostname = re.sub('[ _]', '-', hostname) hostname = re.sub('[^\w.-]+', '', hostname) hostname = hostname.lower() hostname = hostname.strip('.-') return hostname def hash_file(file_like_object): """Generate a hash for the contents of a file.""" checksum = hashlib.sha1() any(map(checksum.update, iter(lambda: file_like_object.read(32768), b''))) return checksum.hexdigest() def service_is_up(service): """Check whether a service is up based on last heartbeat.""" last_heartbeat = service['updated_at'] or service['created_at'] # Timestamps in DB are UTC. elapsed = (timeutils.utcnow(with_timezone=True) - last_heartbeat).total_seconds() return abs(elapsed) <= CONF.service_down_time def read_file_as_root(file_path): """Secure helper to read file as root.""" try: out, _err = execute('cat', file_path, run_as_root=True) return out except processutils.ProcessExecutionError: raise exception.FileNotFound(file_path=file_path) @contextlib.contextmanager def temporary_chown(path, owner_uid=None): """Temporarily chown a path. :params owner_uid: UID of temporary owner (defaults to current user) """ if owner_uid is None: owner_uid = os.getuid() orig_uid = os.stat(path).st_uid if orig_uid != owner_uid: execute('chown', owner_uid, path, run_as_root=True) try: yield finally: if orig_uid != owner_uid: execute('chown', orig_uid, path, run_as_root=True) @contextlib.contextmanager def tempdir(**kwargs): tmpdir = tempfile.mkdtemp(**kwargs) try: yield tmpdir finally: try: shutil.rmtree(tmpdir) except OSError as e: LOG.debug('Could not remove tmpdir: %s', six.text_type(e)) def walk_class_hierarchy(clazz, encountered=None): """Walk class hierarchy, yielding most derived classes first.""" if not encountered: encountered = [] for subclass in clazz.__subclasses__(): if subclass not in encountered: encountered.append(subclass) # drill down to leaves first for subsubclass in walk_class_hierarchy(subclass, encountered): yield subsubclass yield subclass def get_root_helper(): return 'sudo cinder-rootwrap %s' % CONF.rootwrap_config def brick_get_connector_properties(multipath=False, enforce_multipath=False): """Wrapper to automatically set root_helper in brick calls. :param multipath: A boolean indicating whether the connector can support multipath. :param enforce_multipath: If True, it raises exception when multipath=True is specified but multipathd is not running. If False, it falls back to multipath=False when multipathd is not running. """ root_helper = get_root_helper() return connector.get_connector_properties(root_helper, CONF.my_ip, multipath, enforce_multipath) def brick_get_connector(protocol, driver=None, execute=processutils.execute, use_multipath=False, device_scan_attempts=3, *args, **kwargs): """Wrapper to get a brick connector object. This automatically populates the required protocol as well as the root_helper needed to execute commands. """ root_helper = get_root_helper() return connector.InitiatorConnector.factory(protocol, root_helper, driver=driver, execute=execute, use_multipath=use_multipath, device_scan_attempts= device_scan_attempts, *args, **kwargs) def require_driver_initialized(driver): """Verifies if `driver` is initialized If the driver is not initialized, an exception will be raised. :params driver: The driver instance. :raises: `exception.DriverNotInitialized` """ # we can't do anything if the driver didn't init if not driver.initialized: driver_name = driver.__class__.__name__ LOG.error(_LE("Volume driver %s not initialized"), driver_name) raise exception.DriverNotInitialized() def get_file_mode(path): """This primarily exists to make unit testing easier.""" return stat.S_IMODE(os.stat(path).st_mode) def get_file_gid(path): """This primarily exists to make unit testing easier.""" return os.stat(path).st_gid def get_file_size(path): """Returns the file size.""" return os.stat(path).st_size def _get_disk_of_partition(devpath, st=None): """Gets a disk device path and status from partition path. Returns a disk device path from a partition device path, and stat for the device. If devpath is not a partition, devpath is returned as it is. For example, '/dev/sda' is returned for '/dev/sda1', and '/dev/disk1' is for '/dev/disk1p1' ('p' is prepended to the partition number if the disk name ends with numbers). """ diskpath = re.sub('(?:(?<=\d)p)?\d+$', '', devpath) if diskpath != devpath: try: st_disk = os.stat(diskpath) if stat.S_ISBLK(st_disk.st_mode): return (diskpath, st_disk) except OSError: pass # devpath is not a partition if st is None: st = os.stat(devpath) return (devpath, st) def get_bool_param(param_string, params): param = params.get(param_string, False) if not is_valid_boolstr(param): msg = _('Value %(param)s for %(param_string)s is not a ' 'boolean.') % {'param': param, 'param_string': param_string} raise exception.InvalidParameterValue(err=msg) return strutils.bool_from_string(param, strict=True) def get_blkdev_major_minor(path, lookup_for_file=True): """Get 'major:minor' number of block device. Get the device's 'major:minor' number of a block device to control I/O ratelimit of the specified path. If lookup_for_file is True and the path is a regular file, lookup a disk device which the file lies on and returns the result for the device. """ st = os.stat(path) if stat.S_ISBLK(st.st_mode): path, st = _get_disk_of_partition(path, st) return '%d:%d' % (os.major(st.st_rdev), os.minor(st.st_rdev)) elif stat.S_ISCHR(st.st_mode): # No I/O ratelimit control is provided for character devices return None elif lookup_for_file: # lookup the mounted disk which the file lies on out, _err = execute('df', path) devpath = out.split("\n")[1].split()[0] if devpath[0] is not '/': # the file is on a network file system return None return get_blkdev_major_minor(devpath, False) else: msg = _("Unable to get a block device for file \'%s\'") % path raise exception.Error(msg) def check_string_length(value, name, min_length=0, max_length=None): """Check the length of specified string. :param value: the value of the string :param name: the name of the string :param min_length: the min_length of the string :param max_length: the max_length of the string """ if not isinstance(value, six.string_types): msg = _("%s is not a string or unicode") % name raise exception.InvalidInput(message=msg) if len(value) < min_length: msg = _("%(name)s has a minimum character requirement of " "%(min_length)s.") % {'name': name, 'min_length': min_length} raise exception.InvalidInput(message=msg) if max_length and len(value) > max_length: msg = _("%(name)s has more than %(max_length)s " "characters.") % {'name': name, 'max_length': max_length} raise exception.InvalidInput(message=msg) _visible_admin_metadata_keys = ['readonly', 'attached_mode'] def add_visible_admin_metadata(volume): """Add user-visible admin metadata to regular metadata. Extracts the admin metadata keys that are to be made visible to non-administrators, and adds them to the regular metadata structure for the passed-in volume. """ visible_admin_meta = {} if volume.get('volume_admin_metadata'): if isinstance(volume['volume_admin_metadata'], dict): volume_admin_metadata = volume['volume_admin_metadata'] for key in volume_admin_metadata: if key in _visible_admin_metadata_keys: visible_admin_meta[key] = volume_admin_metadata[key] else: for item in volume['volume_admin_metadata']: if item['key'] in _visible_admin_metadata_keys: visible_admin_meta[item['key']] = item['value'] # avoid circular ref when volume is a Volume instance elif (volume.get('admin_metadata') and isinstance(volume.get('admin_metadata'), dict)): for key in _visible_admin_metadata_keys: if key in volume['admin_metadata'].keys(): visible_admin_meta[key] = volume['admin_metadata'][key] if not visible_admin_meta: return # NOTE(zhiyan): update visible administration metadata to # volume metadata, administration metadata will rewrite existing key. if volume.get('volume_metadata'): orig_meta = list(volume.get('volume_metadata')) for item in orig_meta: if item['key'] in visible_admin_meta.keys(): item['value'] = visible_admin_meta.pop(item['key']) for key, value in visible_admin_meta.items(): orig_meta.append({'key': key, 'value': value}) volume['volume_metadata'] = orig_meta # avoid circular ref when vol is a Volume instance elif (volume.get('metadata') and isinstance(volume.get('metadata'), dict)): volume['metadata'].update(visible_admin_meta) else: volume['metadata'] = visible_admin_meta def remove_invalid_filter_options(context, filters, allowed_search_options): """Remove search options that are not valid for non-admin API/context.""" if context.is_admin: # Allow all options return # Otherwise, strip out all unknown options unknown_options = [opt for opt in filters if opt not in allowed_search_options] bad_options = ", ".join(unknown_options) LOG.debug("Removing options '%s' from query.", bad_options) for opt in unknown_options: del filters[opt] def is_blk_device(dev): try: if stat.S_ISBLK(os.stat(dev).st_mode): return True return False except Exception: LOG.debug('Path %s not found in is_blk_device check', dev) return False def retry(exceptions, interval=1, retries=3, backoff_rate=2, wait_random=False): def _retry_on_exception(e): return isinstance(e, exceptions) def _backoff_sleep(previous_attempt_number, delay_since_first_attempt_ms): exp = backoff_rate ** previous_attempt_number wait_for = interval * exp if wait_random: random.seed() wait_val = random.randrange(interval * 1000.0, wait_for * 1000.0) else: wait_val = wait_for * 1000.0 LOG.debug("Sleeping for %s seconds", (wait_val / 1000.0)) return wait_val def _print_stop(previous_attempt_number, delay_since_first_attempt_ms): delay_since_first_attempt = delay_since_first_attempt_ms / 1000.0 LOG.debug("Failed attempt %s", previous_attempt_number) LOG.debug("Have been at this for %s seconds", delay_since_first_attempt) return previous_attempt_number == retries if retries < 1: raise ValueError('Retries must be greater than or ' 'equal to 1 (received: %s). ' % retries) def _decorator(f): @six.wraps(f) def _wrapper(*args, **kwargs): r = retrying.Retrying(retry_on_exception=_retry_on_exception, wait_func=_backoff_sleep, stop_func=_print_stop) return r.call(f, *args, **kwargs) return _wrapper return _decorator def convert_version_to_int(version): try: if isinstance(version, six.string_types): version = convert_version_to_tuple(version) if isinstance(version, tuple): return six.moves.reduce(lambda x, y: (x * 1000) + y, version) except Exception: msg = _("Version %s is invalid.") % version raise exception.CinderException(msg) def convert_version_to_str(version_int): version_numbers = [] factor = 1000 while version_int != 0: version_number = version_int - (version_int // factor * factor) version_numbers.insert(0, six.text_type(version_number)) version_int = version_int // factor return '.'.join(map(str, version_numbers)) def convert_version_to_tuple(version_str): return tuple(int(part) for part in version_str.split('.')) def convert_str(text): """Convert to native string. Convert bytes and Unicode strings to native strings: * convert to bytes on Python 2: encode Unicode using encodeutils.safe_encode() * convert to Unicode on Python 3: decode bytes from UTF-8 """ if six.PY2: return encodeutils.safe_encode(text) else: if isinstance(text, bytes): return text.decode('utf-8') else: return text def trace_method(f): """Decorates a function if TRACE_METHOD is true.""" @functools.wraps(f) def trace_method_logging_wrapper(*args, **kwargs): if TRACE_METHOD: return trace(f)(*args, **kwargs) return f(*args, **kwargs) return trace_method_logging_wrapper def trace_api(f): """Decorates a function if TRACE_API is true.""" @functools.wraps(f) def trace_api_logging_wrapper(*args, **kwargs): if TRACE_API: return trace(f)(*args, **kwargs) return f(*args, **kwargs) return trace_api_logging_wrapper def trace(f): """Trace calls to the decorated function. This decorator should always be defined as the outermost decorator so it is defined last. This is important so it does not interfere with other decorators. Using this decorator on a function will cause its execution to be logged at `DEBUG` level with arguments, return values, and exceptions. :returns a function decorator """ func_name = f.__name__ @functools.wraps(f) def trace_logging_wrapper(*args, **kwargs): if len(args) > 0: maybe_self = args[0] else: maybe_self = kwargs.get('self', None) if maybe_self and hasattr(maybe_self, '__module__'): logger = logging.getLogger(maybe_self.__module__) else: logger = LOG # NOTE(ameade): Don't bother going any further if DEBUG log level # is not enabled for the logger. if not logger.isEnabledFor(py_logging.DEBUG): return f(*args, **kwargs) all_args = inspect.getcallargs(f, *args, **kwargs) logger.debug('==> %(func)s: call %(all_args)r', {'func': func_name, 'all_args': all_args}) start_time = time.time() * 1000 try: result = f(*args, **kwargs) except Exception as exc: total_time = int(round(time.time() * 1000)) - start_time logger.debug('<== %(func)s: exception (%(time)dms) %(exc)r', {'func': func_name, 'time': total_time, 'exc': exc}) raise total_time = int(round(time.time() * 1000)) - start_time logger.debug('<== %(func)s: return (%(time)dms) %(result)r', {'func': func_name, 'time': total_time, 'result': result}) return result return trace_logging_wrapper class TraceWrapperMetaclass(type): """Metaclass that wraps all methods of a class with trace_method. This metaclass will cause every function inside of the class to be decorated with the trace_method decorator. To use the metaclass you define a class like so: @six.add_metaclass(utils.TraceWrapperMetaclass) class MyClass(object): """ def __new__(meta, classname, bases, classDict): newClassDict = {} for attributeName, attribute in classDict.items(): if isinstance(attribute, types.FunctionType): # replace it with a wrapped version attribute = functools.update_wrapper(trace_method(attribute), attribute) newClassDict[attributeName] = attribute return type.__new__(meta, classname, bases, newClassDict) class TraceWrapperWithABCMetaclass(abc.ABCMeta, TraceWrapperMetaclass): """Metaclass that wraps all methods of a class with trace.""" pass def setup_tracing(trace_flags): """Set global variables for each trace flag. Sets variables TRACE_METHOD and TRACE_API, which represent whether to log method and api traces. :param trace_flags: a list of strings """ global TRACE_METHOD global TRACE_API try: trace_flags = [flag.strip() for flag in trace_flags] except TypeError: # Handle when trace_flags is None or a test mock trace_flags = [] for invalid_flag in (set(trace_flags) - VALID_TRACE_FLAGS): LOG.warning(_LW('Invalid trace flag: %s'), invalid_flag) TRACE_METHOD = 'method' in trace_flags TRACE_API = 'api' in trace_flags def resolve_hostname(hostname): """Resolves host name to IP address. Resolves a host name (my.data.point.com) to an IP address (10.12.143.11). This routine also works if the data passed in hostname is already an IP. In this case, the same IP address will be returned. :param hostname: Host name to resolve. :return: IP Address for Host name. """ result = socket.getaddrinfo(hostname, None)[0] (family, socktype, proto, canonname, sockaddr) = result LOG.debug('Asked to resolve hostname %(host)s and got IP %(ip)s.', {'host': hostname, 'ip': sockaddr[0]}) return sockaddr[0]
execute
identifier_name
test_path_utilities.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from nose.tools import ok_ import os from py_utilities.fs.path_utilities import expanded_abspath from py_utilities.fs.path_utilities import filename from py_utilities.fs.path_utilities import get_first_dir_path from py_utilities.fs.path_utilities import get_first_file_path import tempfile import unittest class
(unittest.TestCase): def test_expanded_abspath(self): home = os.environ["HOME"] ok_(expanded_abspath("~") == home) ok_(expanded_abspath("~/foo") == os.path.join(home, 'foo')) ok_(expanded_abspath("/foo") == "/foo") ok_(expanded_abspath("/foo/bar") == "/foo/bar") def test_filename(self): paths = ['/foo/bar/', '/foo/bar', 'foo/bar/', 'foo/bar', '\\foo\\bar\\', '\\foo\\bar', 'foo\\bar\\', 'foo\\bar'] for path in paths: ok_(filename(path) == 'bar') def test_get_first_dir_path(self): dir = tempfile.mkdtemp() home = os.environ["HOME"] fake = '/foo/bar/x/y/z/a' ok_(dir == get_first_dir_path([dir])) ok_(dir == get_first_dir_path([dir, home])) ok_(home == get_first_dir_path([home, dir])) ok_(home == get_first_dir_path([fake, home, dir])) ok_(dir == get_first_dir_path([fake, dir, home])) def test_get_first_file_path(self): f = tempfile.mkstemp()[1] fake = '/foo/bar/x/y/z/a' ok_(f == get_first_file_path([f])) ok_(f == get_first_file_path([f, fake])) ok_(f == get_first_file_path([fake, f])) # vim: filetype=python
TestPath
identifier_name
test_path_utilities.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from nose.tools import ok_ import os from py_utilities.fs.path_utilities import expanded_abspath from py_utilities.fs.path_utilities import filename from py_utilities.fs.path_utilities import get_first_dir_path from py_utilities.fs.path_utilities import get_first_file_path import tempfile import unittest
def test_expanded_abspath(self): home = os.environ["HOME"] ok_(expanded_abspath("~") == home) ok_(expanded_abspath("~/foo") == os.path.join(home, 'foo')) ok_(expanded_abspath("/foo") == "/foo") ok_(expanded_abspath("/foo/bar") == "/foo/bar") def test_filename(self): paths = ['/foo/bar/', '/foo/bar', 'foo/bar/', 'foo/bar', '\\foo\\bar\\', '\\foo\\bar', 'foo\\bar\\', 'foo\\bar'] for path in paths: ok_(filename(path) == 'bar') def test_get_first_dir_path(self): dir = tempfile.mkdtemp() home = os.environ["HOME"] fake = '/foo/bar/x/y/z/a' ok_(dir == get_first_dir_path([dir])) ok_(dir == get_first_dir_path([dir, home])) ok_(home == get_first_dir_path([home, dir])) ok_(home == get_first_dir_path([fake, home, dir])) ok_(dir == get_first_dir_path([fake, dir, home])) def test_get_first_file_path(self): f = tempfile.mkstemp()[1] fake = '/foo/bar/x/y/z/a' ok_(f == get_first_file_path([f])) ok_(f == get_first_file_path([f, fake])) ok_(f == get_first_file_path([fake, f])) # vim: filetype=python
class TestPath(unittest.TestCase):
random_line_split
test_path_utilities.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from nose.tools import ok_ import os from py_utilities.fs.path_utilities import expanded_abspath from py_utilities.fs.path_utilities import filename from py_utilities.fs.path_utilities import get_first_dir_path from py_utilities.fs.path_utilities import get_first_file_path import tempfile import unittest class TestPath(unittest.TestCase): def test_expanded_abspath(self): home = os.environ["HOME"] ok_(expanded_abspath("~") == home) ok_(expanded_abspath("~/foo") == os.path.join(home, 'foo')) ok_(expanded_abspath("/foo") == "/foo") ok_(expanded_abspath("/foo/bar") == "/foo/bar") def test_filename(self): paths = ['/foo/bar/', '/foo/bar', 'foo/bar/', 'foo/bar', '\\foo\\bar\\', '\\foo\\bar', 'foo\\bar\\', 'foo\\bar'] for path in paths:
def test_get_first_dir_path(self): dir = tempfile.mkdtemp() home = os.environ["HOME"] fake = '/foo/bar/x/y/z/a' ok_(dir == get_first_dir_path([dir])) ok_(dir == get_first_dir_path([dir, home])) ok_(home == get_first_dir_path([home, dir])) ok_(home == get_first_dir_path([fake, home, dir])) ok_(dir == get_first_dir_path([fake, dir, home])) def test_get_first_file_path(self): f = tempfile.mkstemp()[1] fake = '/foo/bar/x/y/z/a' ok_(f == get_first_file_path([f])) ok_(f == get_first_file_path([f, fake])) ok_(f == get_first_file_path([fake, f])) # vim: filetype=python
ok_(filename(path) == 'bar')
conditional_block
test_path_utilities.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from nose.tools import ok_ import os from py_utilities.fs.path_utilities import expanded_abspath from py_utilities.fs.path_utilities import filename from py_utilities.fs.path_utilities import get_first_dir_path from py_utilities.fs.path_utilities import get_first_file_path import tempfile import unittest class TestPath(unittest.TestCase): def test_expanded_abspath(self): home = os.environ["HOME"] ok_(expanded_abspath("~") == home) ok_(expanded_abspath("~/foo") == os.path.join(home, 'foo')) ok_(expanded_abspath("/foo") == "/foo") ok_(expanded_abspath("/foo/bar") == "/foo/bar") def test_filename(self): paths = ['/foo/bar/', '/foo/bar', 'foo/bar/', 'foo/bar', '\\foo\\bar\\', '\\foo\\bar', 'foo\\bar\\', 'foo\\bar'] for path in paths: ok_(filename(path) == 'bar') def test_get_first_dir_path(self): dir = tempfile.mkdtemp() home = os.environ["HOME"] fake = '/foo/bar/x/y/z/a' ok_(dir == get_first_dir_path([dir])) ok_(dir == get_first_dir_path([dir, home])) ok_(home == get_first_dir_path([home, dir])) ok_(home == get_first_dir_path([fake, home, dir])) ok_(dir == get_first_dir_path([fake, dir, home])) def test_get_first_file_path(self):
# vim: filetype=python
f = tempfile.mkstemp()[1] fake = '/foo/bar/x/y/z/a' ok_(f == get_first_file_path([f])) ok_(f == get_first_file_path([f, fake])) ok_(f == get_first_file_path([fake, f]))
identifier_body
base.ts
import { assert, unreachable } from '../../../common/util/util.js'; import { kTextureFormatInfo } from '../../capability_info.js'; import { align } from '../../util/math.js'; import { reifyExtent3D } from '../../util/unions.js'; /** * Compute the maximum mip level count allowed for a given texture size and texture dimension. */ export function maxMipLevelCount({ size, dimension = '2d', }: { readonly size: Readonly<GPUExtent3DDict> | readonly number[]; readonly dimension?: GPUTextureDimension; }): number { const sizeDict = reifyExtent3D(size); let maxMippedDimension = 0; switch (dimension) { case '1d': maxMippedDimension = 1; // No mipmaps allowed. break; case '2d': maxMippedDimension = Math.max(sizeDict.width, sizeDict.height); break; case '3d': maxMippedDimension = Math.max(sizeDict.width, sizeDict.height, sizeDict.depthOrArrayLayers); break; } return Math.floor(Math.log2(maxMippedDimension)) + 1; } /** * Compute the "physical size" of a mip level: the size of the level, rounded up to a * multiple of the texel block size. */ export function physicalMipSize( baseSize: Required<GPUExtent3DDict>, format: GPUTextureFormat, dimension: GPUTextureDimension, level: number ): Required<GPUExtent3DDict> { switch (dimension) { case '1d': assert(level === 0 && baseSize.height === 1 && baseSize.depthOrArrayLayers === 1); return { width: baseSize.width, height: 1, depthOrArrayLayers: 1 }; case '2d': { assert(Math.max(baseSize.width, baseSize.height) >> level > 0); const virtualWidthAtLevel = Math.max(baseSize.width >> level, 1); const virtualHeightAtLevel = Math.max(baseSize.height >> level, 1); const physicalWidthAtLevel = align( virtualWidthAtLevel, kTextureFormatInfo[format].blockWidth ); const physicalHeightAtLevel = align( virtualHeightAtLevel, kTextureFormatInfo[format].blockHeight ); return { width: physicalWidthAtLevel, height: physicalHeightAtLevel, depthOrArrayLayers: baseSize.depthOrArrayLayers, }; } case '3d': { assert(Math.max(baseSize.width, baseSize.height, baseSize.depthOrArrayLayers) >> level > 0); assert( kTextureFormatInfo[format].blockWidth === 1 && kTextureFormatInfo[format].blockHeight === 1 ); return { width: Math.max(baseSize.width >> level, 1), height: Math.max(baseSize.height >> level, 1), depthOrArrayLayers: Math.max(baseSize.depthOrArrayLayers >> level, 1), }; } } } /** * Compute the "virtual size" of a mip level of a texture (not accounting for texel block rounding). */ export function virtualMipSize( dimension: GPUTextureDimension, size: readonly [number, number, number], mipLevel: number ): [number, number, number] { const shiftMinOne = (n: number) => Math.max(1, n >> mipLevel); switch (dimension) { case '1d': assert(size[2] === 1); return [shiftMinOne(size[0]), size[1], size[2]]; case '2d': return [shiftMinOne(size[0]), shiftMinOne(size[1]), size[2]]; case '3d': return [shiftMinOne(size[0]), shiftMinOne(size[1]), shiftMinOne(size[2])]; default: unreachable(); } } /** * Get texture dimension from view dimension in order to create an compatible texture for a given * view dimension. */ export function getTextureDimensionFromView(viewDimension: GPUTextureViewDimension) { switch (viewDimension) { case '1d': return '1d'; case '2d': case '2d-array': case 'cube': case 'cube-array': return '2d'; case '3d': return '3d'; default: unreachable(); } } /** Returns the possible valid view dimensions for a given texture dimension. */ export function viewDimensionsForTextureDimension(textureDimension: GPUTextureDimension) { switch (textureDimension) { case '1d': return ['1d'] as const; case '2d': return ['2d', '2d-array', 'cube', 'cube-array'] as const; case '3d': return ['3d'] as const; } } /** Reifies the optional fields of `GPUTextureDescriptor`. * MAINTENANCE_TODO: viewFormats should not be omitted here, but it seems likely that the * @webgpu/types definition will have to change before we can include it again. */ export function reifyTextureDescriptor( desc: Readonly<GPUTextureDescriptor> ): Required<Omit<GPUTextureDescriptor, 'label' | 'viewFormats'>> { return { dimension: '2d' as const, mipLevelCount: 1, sampleCount: 1, ...desc }; } /** Reifies the optional fields of `GPUTextureViewDescriptor` (given a `GPUTextureDescriptor`). */ export function reifyTextureViewDescriptor( textureDescriptor: Readonly<GPUTextureDescriptor>, view: Readonly<GPUTextureViewDescriptor> ): Required<Omit<GPUTextureViewDescriptor, 'label'>> { const texture = reifyTextureDescriptor(textureDescriptor); // IDL defaulting const baseMipLevel = view.baseMipLevel ?? 0; const baseArrayLayer = view.baseArrayLayer ?? 0; const aspect = view.aspect ?? 'all'; // Spec defaulting const format = view.format ?? texture.format; const mipLevelCount = view.mipLevelCount ?? texture.mipLevelCount - baseMipLevel; const dimension = view.dimension ?? texture.dimension; let arrayLayerCount = view.arrayLayerCount; if (arrayLayerCount === undefined) { if (dimension === '2d-array' || dimension === 'cube-array')
else if (dimension === 'cube') { arrayLayerCount = 6; } else { arrayLayerCount = 1; } } return { format, dimension, aspect, baseMipLevel, mipLevelCount, baseArrayLayer, arrayLayerCount, }; }
{ arrayLayerCount = reifyExtent3D(texture.size).depthOrArrayLayers - baseArrayLayer; }
conditional_block
base.ts
import { assert, unreachable } from '../../../common/util/util.js'; import { kTextureFormatInfo } from '../../capability_info.js'; import { align } from '../../util/math.js'; import { reifyExtent3D } from '../../util/unions.js'; /** * Compute the maximum mip level count allowed for a given texture size and texture dimension. */ export function maxMipLevelCount({ size, dimension = '2d', }: { readonly size: Readonly<GPUExtent3DDict> | readonly number[]; readonly dimension?: GPUTextureDimension; }): number { const sizeDict = reifyExtent3D(size); let maxMippedDimension = 0; switch (dimension) { case '1d': maxMippedDimension = 1; // No mipmaps allowed. break; case '2d': maxMippedDimension = Math.max(sizeDict.width, sizeDict.height); break; case '3d': maxMippedDimension = Math.max(sizeDict.width, sizeDict.height, sizeDict.depthOrArrayLayers); break; } return Math.floor(Math.log2(maxMippedDimension)) + 1; } /** * Compute the "physical size" of a mip level: the size of the level, rounded up to a * multiple of the texel block size. */ export function physicalMipSize( baseSize: Required<GPUExtent3DDict>, format: GPUTextureFormat, dimension: GPUTextureDimension, level: number ): Required<GPUExtent3DDict> { switch (dimension) { case '1d': assert(level === 0 && baseSize.height === 1 && baseSize.depthOrArrayLayers === 1); return { width: baseSize.width, height: 1, depthOrArrayLayers: 1 }; case '2d': { assert(Math.max(baseSize.width, baseSize.height) >> level > 0); const virtualWidthAtLevel = Math.max(baseSize.width >> level, 1); const virtualHeightAtLevel = Math.max(baseSize.height >> level, 1); const physicalWidthAtLevel = align( virtualWidthAtLevel, kTextureFormatInfo[format].blockWidth ); const physicalHeightAtLevel = align( virtualHeightAtLevel, kTextureFormatInfo[format].blockHeight ); return { width: physicalWidthAtLevel, height: physicalHeightAtLevel, depthOrArrayLayers: baseSize.depthOrArrayLayers, }; } case '3d': { assert(Math.max(baseSize.width, baseSize.height, baseSize.depthOrArrayLayers) >> level > 0); assert( kTextureFormatInfo[format].blockWidth === 1 && kTextureFormatInfo[format].blockHeight === 1 ); return { width: Math.max(baseSize.width >> level, 1), height: Math.max(baseSize.height >> level, 1), depthOrArrayLayers: Math.max(baseSize.depthOrArrayLayers >> level, 1), }; } } } /** * Compute the "virtual size" of a mip level of a texture (not accounting for texel block rounding). */ export function virtualMipSize( dimension: GPUTextureDimension, size: readonly [number, number, number], mipLevel: number ): [number, number, number] { const shiftMinOne = (n: number) => Math.max(1, n >> mipLevel); switch (dimension) { case '1d': assert(size[2] === 1); return [shiftMinOne(size[0]), size[1], size[2]]; case '2d': return [shiftMinOne(size[0]), shiftMinOne(size[1]), size[2]]; case '3d': return [shiftMinOne(size[0]), shiftMinOne(size[1]), shiftMinOne(size[2])]; default: unreachable(); } } /** * Get texture dimension from view dimension in order to create an compatible texture for a given * view dimension. */ export function getTextureDimensionFromView(viewDimension: GPUTextureViewDimension) { switch (viewDimension) { case '1d': return '1d'; case '2d': case '2d-array': case 'cube': case 'cube-array': return '2d'; case '3d': return '3d'; default: unreachable(); } } /** Returns the possible valid view dimensions for a given texture dimension. */ export function viewDimensionsForTextureDimension(textureDimension: GPUTextureDimension) { switch (textureDimension) { case '1d': return ['1d'] as const; case '2d': return ['2d', '2d-array', 'cube', 'cube-array'] as const;
/** Reifies the optional fields of `GPUTextureDescriptor`. * MAINTENANCE_TODO: viewFormats should not be omitted here, but it seems likely that the * @webgpu/types definition will have to change before we can include it again. */ export function reifyTextureDescriptor( desc: Readonly<GPUTextureDescriptor> ): Required<Omit<GPUTextureDescriptor, 'label' | 'viewFormats'>> { return { dimension: '2d' as const, mipLevelCount: 1, sampleCount: 1, ...desc }; } /** Reifies the optional fields of `GPUTextureViewDescriptor` (given a `GPUTextureDescriptor`). */ export function reifyTextureViewDescriptor( textureDescriptor: Readonly<GPUTextureDescriptor>, view: Readonly<GPUTextureViewDescriptor> ): Required<Omit<GPUTextureViewDescriptor, 'label'>> { const texture = reifyTextureDescriptor(textureDescriptor); // IDL defaulting const baseMipLevel = view.baseMipLevel ?? 0; const baseArrayLayer = view.baseArrayLayer ?? 0; const aspect = view.aspect ?? 'all'; // Spec defaulting const format = view.format ?? texture.format; const mipLevelCount = view.mipLevelCount ?? texture.mipLevelCount - baseMipLevel; const dimension = view.dimension ?? texture.dimension; let arrayLayerCount = view.arrayLayerCount; if (arrayLayerCount === undefined) { if (dimension === '2d-array' || dimension === 'cube-array') { arrayLayerCount = reifyExtent3D(texture.size).depthOrArrayLayers - baseArrayLayer; } else if (dimension === 'cube') { arrayLayerCount = 6; } else { arrayLayerCount = 1; } } return { format, dimension, aspect, baseMipLevel, mipLevelCount, baseArrayLayer, arrayLayerCount, }; }
case '3d': return ['3d'] as const; } }
random_line_split
base.ts
import { assert, unreachable } from '../../../common/util/util.js'; import { kTextureFormatInfo } from '../../capability_info.js'; import { align } from '../../util/math.js'; import { reifyExtent3D } from '../../util/unions.js'; /** * Compute the maximum mip level count allowed for a given texture size and texture dimension. */ export function
({ size, dimension = '2d', }: { readonly size: Readonly<GPUExtent3DDict> | readonly number[]; readonly dimension?: GPUTextureDimension; }): number { const sizeDict = reifyExtent3D(size); let maxMippedDimension = 0; switch (dimension) { case '1d': maxMippedDimension = 1; // No mipmaps allowed. break; case '2d': maxMippedDimension = Math.max(sizeDict.width, sizeDict.height); break; case '3d': maxMippedDimension = Math.max(sizeDict.width, sizeDict.height, sizeDict.depthOrArrayLayers); break; } return Math.floor(Math.log2(maxMippedDimension)) + 1; } /** * Compute the "physical size" of a mip level: the size of the level, rounded up to a * multiple of the texel block size. */ export function physicalMipSize( baseSize: Required<GPUExtent3DDict>, format: GPUTextureFormat, dimension: GPUTextureDimension, level: number ): Required<GPUExtent3DDict> { switch (dimension) { case '1d': assert(level === 0 && baseSize.height === 1 && baseSize.depthOrArrayLayers === 1); return { width: baseSize.width, height: 1, depthOrArrayLayers: 1 }; case '2d': { assert(Math.max(baseSize.width, baseSize.height) >> level > 0); const virtualWidthAtLevel = Math.max(baseSize.width >> level, 1); const virtualHeightAtLevel = Math.max(baseSize.height >> level, 1); const physicalWidthAtLevel = align( virtualWidthAtLevel, kTextureFormatInfo[format].blockWidth ); const physicalHeightAtLevel = align( virtualHeightAtLevel, kTextureFormatInfo[format].blockHeight ); return { width: physicalWidthAtLevel, height: physicalHeightAtLevel, depthOrArrayLayers: baseSize.depthOrArrayLayers, }; } case '3d': { assert(Math.max(baseSize.width, baseSize.height, baseSize.depthOrArrayLayers) >> level > 0); assert( kTextureFormatInfo[format].blockWidth === 1 && kTextureFormatInfo[format].blockHeight === 1 ); return { width: Math.max(baseSize.width >> level, 1), height: Math.max(baseSize.height >> level, 1), depthOrArrayLayers: Math.max(baseSize.depthOrArrayLayers >> level, 1), }; } } } /** * Compute the "virtual size" of a mip level of a texture (not accounting for texel block rounding). */ export function virtualMipSize( dimension: GPUTextureDimension, size: readonly [number, number, number], mipLevel: number ): [number, number, number] { const shiftMinOne = (n: number) => Math.max(1, n >> mipLevel); switch (dimension) { case '1d': assert(size[2] === 1); return [shiftMinOne(size[0]), size[1], size[2]]; case '2d': return [shiftMinOne(size[0]), shiftMinOne(size[1]), size[2]]; case '3d': return [shiftMinOne(size[0]), shiftMinOne(size[1]), shiftMinOne(size[2])]; default: unreachable(); } } /** * Get texture dimension from view dimension in order to create an compatible texture for a given * view dimension. */ export function getTextureDimensionFromView(viewDimension: GPUTextureViewDimension) { switch (viewDimension) { case '1d': return '1d'; case '2d': case '2d-array': case 'cube': case 'cube-array': return '2d'; case '3d': return '3d'; default: unreachable(); } } /** Returns the possible valid view dimensions for a given texture dimension. */ export function viewDimensionsForTextureDimension(textureDimension: GPUTextureDimension) { switch (textureDimension) { case '1d': return ['1d'] as const; case '2d': return ['2d', '2d-array', 'cube', 'cube-array'] as const; case '3d': return ['3d'] as const; } } /** Reifies the optional fields of `GPUTextureDescriptor`. * MAINTENANCE_TODO: viewFormats should not be omitted here, but it seems likely that the * @webgpu/types definition will have to change before we can include it again. */ export function reifyTextureDescriptor( desc: Readonly<GPUTextureDescriptor> ): Required<Omit<GPUTextureDescriptor, 'label' | 'viewFormats'>> { return { dimension: '2d' as const, mipLevelCount: 1, sampleCount: 1, ...desc }; } /** Reifies the optional fields of `GPUTextureViewDescriptor` (given a `GPUTextureDescriptor`). */ export function reifyTextureViewDescriptor( textureDescriptor: Readonly<GPUTextureDescriptor>, view: Readonly<GPUTextureViewDescriptor> ): Required<Omit<GPUTextureViewDescriptor, 'label'>> { const texture = reifyTextureDescriptor(textureDescriptor); // IDL defaulting const baseMipLevel = view.baseMipLevel ?? 0; const baseArrayLayer = view.baseArrayLayer ?? 0; const aspect = view.aspect ?? 'all'; // Spec defaulting const format = view.format ?? texture.format; const mipLevelCount = view.mipLevelCount ?? texture.mipLevelCount - baseMipLevel; const dimension = view.dimension ?? texture.dimension; let arrayLayerCount = view.arrayLayerCount; if (arrayLayerCount === undefined) { if (dimension === '2d-array' || dimension === 'cube-array') { arrayLayerCount = reifyExtent3D(texture.size).depthOrArrayLayers - baseArrayLayer; } else if (dimension === 'cube') { arrayLayerCount = 6; } else { arrayLayerCount = 1; } } return { format, dimension, aspect, baseMipLevel, mipLevelCount, baseArrayLayer, arrayLayerCount, }; }
maxMipLevelCount
identifier_name
base.ts
import { assert, unreachable } from '../../../common/util/util.js'; import { kTextureFormatInfo } from '../../capability_info.js'; import { align } from '../../util/math.js'; import { reifyExtent3D } from '../../util/unions.js'; /** * Compute the maximum mip level count allowed for a given texture size and texture dimension. */ export function maxMipLevelCount({ size, dimension = '2d', }: { readonly size: Readonly<GPUExtent3DDict> | readonly number[]; readonly dimension?: GPUTextureDimension; }): number { const sizeDict = reifyExtent3D(size); let maxMippedDimension = 0; switch (dimension) { case '1d': maxMippedDimension = 1; // No mipmaps allowed. break; case '2d': maxMippedDimension = Math.max(sizeDict.width, sizeDict.height); break; case '3d': maxMippedDimension = Math.max(sizeDict.width, sizeDict.height, sizeDict.depthOrArrayLayers); break; } return Math.floor(Math.log2(maxMippedDimension)) + 1; } /** * Compute the "physical size" of a mip level: the size of the level, rounded up to a * multiple of the texel block size. */ export function physicalMipSize( baseSize: Required<GPUExtent3DDict>, format: GPUTextureFormat, dimension: GPUTextureDimension, level: number ): Required<GPUExtent3DDict>
/** * Compute the "virtual size" of a mip level of a texture (not accounting for texel block rounding). */ export function virtualMipSize( dimension: GPUTextureDimension, size: readonly [number, number, number], mipLevel: number ): [number, number, number] { const shiftMinOne = (n: number) => Math.max(1, n >> mipLevel); switch (dimension) { case '1d': assert(size[2] === 1); return [shiftMinOne(size[0]), size[1], size[2]]; case '2d': return [shiftMinOne(size[0]), shiftMinOne(size[1]), size[2]]; case '3d': return [shiftMinOne(size[0]), shiftMinOne(size[1]), shiftMinOne(size[2])]; default: unreachable(); } } /** * Get texture dimension from view dimension in order to create an compatible texture for a given * view dimension. */ export function getTextureDimensionFromView(viewDimension: GPUTextureViewDimension) { switch (viewDimension) { case '1d': return '1d'; case '2d': case '2d-array': case 'cube': case 'cube-array': return '2d'; case '3d': return '3d'; default: unreachable(); } } /** Returns the possible valid view dimensions for a given texture dimension. */ export function viewDimensionsForTextureDimension(textureDimension: GPUTextureDimension) { switch (textureDimension) { case '1d': return ['1d'] as const; case '2d': return ['2d', '2d-array', 'cube', 'cube-array'] as const; case '3d': return ['3d'] as const; } } /** Reifies the optional fields of `GPUTextureDescriptor`. * MAINTENANCE_TODO: viewFormats should not be omitted here, but it seems likely that the * @webgpu/types definition will have to change before we can include it again. */ export function reifyTextureDescriptor( desc: Readonly<GPUTextureDescriptor> ): Required<Omit<GPUTextureDescriptor, 'label' | 'viewFormats'>> { return { dimension: '2d' as const, mipLevelCount: 1, sampleCount: 1, ...desc }; } /** Reifies the optional fields of `GPUTextureViewDescriptor` (given a `GPUTextureDescriptor`). */ export function reifyTextureViewDescriptor( textureDescriptor: Readonly<GPUTextureDescriptor>, view: Readonly<GPUTextureViewDescriptor> ): Required<Omit<GPUTextureViewDescriptor, 'label'>> { const texture = reifyTextureDescriptor(textureDescriptor); // IDL defaulting const baseMipLevel = view.baseMipLevel ?? 0; const baseArrayLayer = view.baseArrayLayer ?? 0; const aspect = view.aspect ?? 'all'; // Spec defaulting const format = view.format ?? texture.format; const mipLevelCount = view.mipLevelCount ?? texture.mipLevelCount - baseMipLevel; const dimension = view.dimension ?? texture.dimension; let arrayLayerCount = view.arrayLayerCount; if (arrayLayerCount === undefined) { if (dimension === '2d-array' || dimension === 'cube-array') { arrayLayerCount = reifyExtent3D(texture.size).depthOrArrayLayers - baseArrayLayer; } else if (dimension === 'cube') { arrayLayerCount = 6; } else { arrayLayerCount = 1; } } return { format, dimension, aspect, baseMipLevel, mipLevelCount, baseArrayLayer, arrayLayerCount, }; }
{ switch (dimension) { case '1d': assert(level === 0 && baseSize.height === 1 && baseSize.depthOrArrayLayers === 1); return { width: baseSize.width, height: 1, depthOrArrayLayers: 1 }; case '2d': { assert(Math.max(baseSize.width, baseSize.height) >> level > 0); const virtualWidthAtLevel = Math.max(baseSize.width >> level, 1); const virtualHeightAtLevel = Math.max(baseSize.height >> level, 1); const physicalWidthAtLevel = align( virtualWidthAtLevel, kTextureFormatInfo[format].blockWidth ); const physicalHeightAtLevel = align( virtualHeightAtLevel, kTextureFormatInfo[format].blockHeight ); return { width: physicalWidthAtLevel, height: physicalHeightAtLevel, depthOrArrayLayers: baseSize.depthOrArrayLayers, }; } case '3d': { assert(Math.max(baseSize.width, baseSize.height, baseSize.depthOrArrayLayers) >> level > 0); assert( kTextureFormatInfo[format].blockWidth === 1 && kTextureFormatInfo[format].blockHeight === 1 ); return { width: Math.max(baseSize.width >> level, 1), height: Math.max(baseSize.height >> level, 1), depthOrArrayLayers: Math.max(baseSize.depthOrArrayLayers >> level, 1), }; } } }
identifier_body
0012_auto_20160411_1630.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-04-11 14:30 from __future__ import unicode_literals from django.db import migrations import isi_mip.choiceorotherfield.models class Migration(migrations.Migration):
dependencies = [ ('climatemodels', '0011_auto_20160407_1050'), ] operations = [ migrations.AlterField( model_name='impactmodel', name='resolution', field=isi_mip.choiceorotherfield.models.ChoiceOrOtherField(blank=True, choices=[('0.5°x0.5°', '0.5°x0.5°')], help_text='The spatial resolution at which the ISIMIP simulations were run, if on a regular grid. Data was provided on a 0.5°x0.5° grid', max_length=500, null=True, verbose_name='Spatial Resolution'), ), ]
identifier_body
0012_auto_20160411_1630.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-04-11 14:30 from __future__ import unicode_literals from django.db import migrations import isi_mip.choiceorotherfield.models class
(migrations.Migration): dependencies = [ ('climatemodels', '0011_auto_20160407_1050'), ] operations = [ migrations.AlterField( model_name='impactmodel', name='resolution', field=isi_mip.choiceorotherfield.models.ChoiceOrOtherField(blank=True, choices=[('0.5°x0.5°', '0.5°x0.5°')], help_text='The spatial resolution at which the ISIMIP simulations were run, if on a regular grid. Data was provided on a 0.5°x0.5° grid', max_length=500, null=True, verbose_name='Spatial Resolution'), ), ]
Migration
identifier_name
0012_auto_20160411_1630.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-04-11 14:30 from __future__ import unicode_literals from django.db import migrations import isi_mip.choiceorotherfield.models
dependencies = [ ('climatemodels', '0011_auto_20160407_1050'), ] operations = [ migrations.AlterField( model_name='impactmodel', name='resolution', field=isi_mip.choiceorotherfield.models.ChoiceOrOtherField(blank=True, choices=[('0.5°x0.5°', '0.5°x0.5°')], help_text='The spatial resolution at which the ISIMIP simulations were run, if on a regular grid. Data was provided on a 0.5°x0.5° grid', max_length=500, null=True, verbose_name='Spatial Resolution'), ), ]
class Migration(migrations.Migration):
random_line_split
SSR.test.tsx
/** * @jest-environment node */ import { renderToString } from 'react-dom/server' import { IS_BROWSER } from '../src/utils/isBrowser' import { now } from '../src/utils/now' import { DEFAULT_ELEMENT } from '../src/utils/defaults' import { useIdleTimer } from '../src/useIdleTimer' describe('Server Side Rendering', () => { it('Should return that environment is not a browser', () => { expect(IS_BROWSER).toBe(false) }) it('Should return a null default element', () => { expect(DEFAULT_ELEMENT).toBe(null) })
it('Should not bind events', () => { const App = () => { const idleTimer = useIdleTimer() idleTimer.start() idleTimer.pause() return ( <div>{idleTimer.isIdle()}</div> ) } expect(() => renderToString(<App />)).not.toThrow() }) })
it('Should return now', () => { expect(now()).toBeDefined() })
random_line_split
absurd_extreme_comparisons.rs
use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; use clippy_utils::comparisons::{normalize_comparison, Rel}; use clippy_utils::consts::{constant, Constant}; use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::source::snippet; use clippy_utils::ty::is_isize_or_usize; use clippy_utils::{clip, int_bits, unsext}; declare_clippy_lint! { /// ### What it does /// Checks for comparisons where one side of the relation is /// either the minimum or maximum value for its type and warns if it involves a /// case that is always true or always false. Only integer and boolean types are /// checked. /// /// ### Why is this bad? /// An expression like `min <= x` may misleadingly imply /// that it is possible for `x` to be less than the minimum. Expressions like /// `max < x` are probably mistakes. /// /// ### Known problems /// For `usize` the size of the current compile target will /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such /// a comparison to detect target pointer width will trigger this lint. One can /// use `mem::sizeof` and compare its value or conditional compilation /// attributes /// like `#[cfg(target_pointer_width = "64")] ..` instead. /// /// ### Example /// ```rust /// let vec: Vec<isize> = Vec::new(); /// if vec.len() <= 0 {} /// if 100 > i32::MAX {} /// ``` pub ABSURD_EXTREME_COMPARISONS, correctness, "a comparison with a maximum or minimum value that is always true or false" } declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]); impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if let ExprKind::Binary(ref cmp, lhs, rhs) = expr.kind { if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) { if !expr.span.from_expansion() { let msg = "this comparison involving the minimum or maximum element for this \ type contains a case that is always true or always false"; let conclusion = match result { AbsurdComparisonResult::AlwaysFalse => "this comparison is always false".to_owned(), AbsurdComparisonResult::AlwaysTrue => "this comparison is always true".to_owned(), AbsurdComparisonResult::InequalityImpossible => format!( "the case where the two sides are not equal never occurs, consider using `{} == {}` \ instead", snippet(cx, lhs.span, "lhs"), snippet(cx, rhs.span, "rhs") ), }; let help = format!( "because `{}` is the {} value for this type, {}", snippet(cx, culprit.expr.span, "x"), match culprit.which { ExtremeType::Minimum => "minimum", ExtremeType::Maximum => "maximum", }, conclusion ); span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help); } } } } } enum ExtremeType { Minimum, Maximum, } struct ExtremeExpr<'a> { which: ExtremeType, expr: &'a Expr<'a>, } enum AbsurdComparisonResult { AlwaysFalse, AlwaysTrue, InequalityImpossible, } fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool { if let ExprKind::Cast(cast_exp, _) = expr.kind { let precast_ty = cx.typeck_results().expr_ty(cast_exp); let cast_ty = cx.typeck_results().expr_ty(expr); return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty); } false } fn detect_absurd_comparison<'tcx>( cx: &LateContext<'tcx>, op: BinOpKind, lhs: &'tcx Expr<'_>, rhs: &'tcx Expr<'_>, ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> { use AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible}; use ExtremeType::{Maximum, Minimum}; // absurd comparison only makes sense on primitive types // primitive types don't implement comparison operators with each other if cx.typeck_results().expr_ty(lhs) != cx.typeck_results().expr_ty(rhs) { return None; } // comparisons between fix sized types and target sized types are considered unanalyzable if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) { return None; } let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?; let lx = detect_extreme_expr(cx, normalized_lhs); let rx = detect_extreme_expr(cx, normalized_rhs); Some(match rel { Rel::Lt => { match (lx, rx) { (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min _ => return None, } }, Rel::Le => { match (lx, rx) { (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max _ => return None, } }, Rel::Ne | Rel::Eq => return None, }) } fn detect_extreme_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> { let ty = cx.typeck_results().expr_ty(expr); let cv = constant(cx, cx.typeck_results(), expr)?.0; let which = match (ty.kind(), cv) { (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => ExtremeType::Minimum, (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => { ExtremeType::Minimum }, (&ty::Bool, Constant::Bool(true)) => ExtremeType::Maximum, (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => { ExtremeType::Maximum }, (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::MAX, uty) == i => ExtremeType::Maximum, _ => return None, }; Some(ExtremeExpr { which, expr })
}
random_line_split
absurd_extreme_comparisons.rs
use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; use clippy_utils::comparisons::{normalize_comparison, Rel}; use clippy_utils::consts::{constant, Constant}; use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::source::snippet; use clippy_utils::ty::is_isize_or_usize; use clippy_utils::{clip, int_bits, unsext}; declare_clippy_lint! { /// ### What it does /// Checks for comparisons where one side of the relation is /// either the minimum or maximum value for its type and warns if it involves a /// case that is always true or always false. Only integer and boolean types are /// checked. /// /// ### Why is this bad? /// An expression like `min <= x` may misleadingly imply /// that it is possible for `x` to be less than the minimum. Expressions like /// `max < x` are probably mistakes. /// /// ### Known problems /// For `usize` the size of the current compile target will /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such /// a comparison to detect target pointer width will trigger this lint. One can /// use `mem::sizeof` and compare its value or conditional compilation /// attributes /// like `#[cfg(target_pointer_width = "64")] ..` instead. /// /// ### Example /// ```rust /// let vec: Vec<isize> = Vec::new(); /// if vec.len() <= 0 {} /// if 100 > i32::MAX {} /// ``` pub ABSURD_EXTREME_COMPARISONS, correctness, "a comparison with a maximum or minimum value that is always true or false" } declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]); impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if let ExprKind::Binary(ref cmp, lhs, rhs) = expr.kind { if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) { if !expr.span.from_expansion() { let msg = "this comparison involving the minimum or maximum element for this \ type contains a case that is always true or always false"; let conclusion = match result { AbsurdComparisonResult::AlwaysFalse => "this comparison is always false".to_owned(), AbsurdComparisonResult::AlwaysTrue => "this comparison is always true".to_owned(), AbsurdComparisonResult::InequalityImpossible => format!( "the case where the two sides are not equal never occurs, consider using `{} == {}` \ instead", snippet(cx, lhs.span, "lhs"), snippet(cx, rhs.span, "rhs") ), }; let help = format!( "because `{}` is the {} value for this type, {}", snippet(cx, culprit.expr.span, "x"), match culprit.which { ExtremeType::Minimum => "minimum", ExtremeType::Maximum => "maximum", }, conclusion ); span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help); } } } } } enum
{ Minimum, Maximum, } struct ExtremeExpr<'a> { which: ExtremeType, expr: &'a Expr<'a>, } enum AbsurdComparisonResult { AlwaysFalse, AlwaysTrue, InequalityImpossible, } fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool { if let ExprKind::Cast(cast_exp, _) = expr.kind { let precast_ty = cx.typeck_results().expr_ty(cast_exp); let cast_ty = cx.typeck_results().expr_ty(expr); return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty); } false } fn detect_absurd_comparison<'tcx>( cx: &LateContext<'tcx>, op: BinOpKind, lhs: &'tcx Expr<'_>, rhs: &'tcx Expr<'_>, ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> { use AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible}; use ExtremeType::{Maximum, Minimum}; // absurd comparison only makes sense on primitive types // primitive types don't implement comparison operators with each other if cx.typeck_results().expr_ty(lhs) != cx.typeck_results().expr_ty(rhs) { return None; } // comparisons between fix sized types and target sized types are considered unanalyzable if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) { return None; } let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?; let lx = detect_extreme_expr(cx, normalized_lhs); let rx = detect_extreme_expr(cx, normalized_rhs); Some(match rel { Rel::Lt => { match (lx, rx) { (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min _ => return None, } }, Rel::Le => { match (lx, rx) { (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max _ => return None, } }, Rel::Ne | Rel::Eq => return None, }) } fn detect_extreme_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> { let ty = cx.typeck_results().expr_ty(expr); let cv = constant(cx, cx.typeck_results(), expr)?.0; let which = match (ty.kind(), cv) { (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => ExtremeType::Minimum, (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => { ExtremeType::Minimum }, (&ty::Bool, Constant::Bool(true)) => ExtremeType::Maximum, (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => { ExtremeType::Maximum }, (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::MAX, uty) == i => ExtremeType::Maximum, _ => return None, }; Some(ExtremeExpr { which, expr }) }
ExtremeType
identifier_name
absurd_extreme_comparisons.rs
use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; use clippy_utils::comparisons::{normalize_comparison, Rel}; use clippy_utils::consts::{constant, Constant}; use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::source::snippet; use clippy_utils::ty::is_isize_or_usize; use clippy_utils::{clip, int_bits, unsext}; declare_clippy_lint! { /// ### What it does /// Checks for comparisons where one side of the relation is /// either the minimum or maximum value for its type and warns if it involves a /// case that is always true or always false. Only integer and boolean types are /// checked. /// /// ### Why is this bad? /// An expression like `min <= x` may misleadingly imply /// that it is possible for `x` to be less than the minimum. Expressions like /// `max < x` are probably mistakes. /// /// ### Known problems /// For `usize` the size of the current compile target will /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such /// a comparison to detect target pointer width will trigger this lint. One can /// use `mem::sizeof` and compare its value or conditional compilation /// attributes /// like `#[cfg(target_pointer_width = "64")] ..` instead. /// /// ### Example /// ```rust /// let vec: Vec<isize> = Vec::new(); /// if vec.len() <= 0 {} /// if 100 > i32::MAX {} /// ``` pub ABSURD_EXTREME_COMPARISONS, correctness, "a comparison with a maximum or minimum value that is always true or false" } declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]); impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if let ExprKind::Binary(ref cmp, lhs, rhs) = expr.kind { if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) { if !expr.span.from_expansion() { let msg = "this comparison involving the minimum or maximum element for this \ type contains a case that is always true or always false"; let conclusion = match result { AbsurdComparisonResult::AlwaysFalse => "this comparison is always false".to_owned(), AbsurdComparisonResult::AlwaysTrue => "this comparison is always true".to_owned(), AbsurdComparisonResult::InequalityImpossible => format!( "the case where the two sides are not equal never occurs, consider using `{} == {}` \ instead", snippet(cx, lhs.span, "lhs"), snippet(cx, rhs.span, "rhs") ), }; let help = format!( "because `{}` is the {} value for this type, {}", snippet(cx, culprit.expr.span, "x"), match culprit.which { ExtremeType::Minimum => "minimum", ExtremeType::Maximum => "maximum", }, conclusion ); span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help); } } } } } enum ExtremeType { Minimum, Maximum, } struct ExtremeExpr<'a> { which: ExtremeType, expr: &'a Expr<'a>, } enum AbsurdComparisonResult { AlwaysFalse, AlwaysTrue, InequalityImpossible, } fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool
fn detect_absurd_comparison<'tcx>( cx: &LateContext<'tcx>, op: BinOpKind, lhs: &'tcx Expr<'_>, rhs: &'tcx Expr<'_>, ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> { use AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible}; use ExtremeType::{Maximum, Minimum}; // absurd comparison only makes sense on primitive types // primitive types don't implement comparison operators with each other if cx.typeck_results().expr_ty(lhs) != cx.typeck_results().expr_ty(rhs) { return None; } // comparisons between fix sized types and target sized types are considered unanalyzable if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) { return None; } let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?; let lx = detect_extreme_expr(cx, normalized_lhs); let rx = detect_extreme_expr(cx, normalized_rhs); Some(match rel { Rel::Lt => { match (lx, rx) { (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min _ => return None, } }, Rel::Le => { match (lx, rx) { (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max _ => return None, } }, Rel::Ne | Rel::Eq => return None, }) } fn detect_extreme_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> { let ty = cx.typeck_results().expr_ty(expr); let cv = constant(cx, cx.typeck_results(), expr)?.0; let which = match (ty.kind(), cv) { (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => ExtremeType::Minimum, (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => { ExtremeType::Minimum }, (&ty::Bool, Constant::Bool(true)) => ExtremeType::Maximum, (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => { ExtremeType::Maximum }, (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::MAX, uty) == i => ExtremeType::Maximum, _ => return None, }; Some(ExtremeExpr { which, expr }) }
{ if let ExprKind::Cast(cast_exp, _) = expr.kind { let precast_ty = cx.typeck_results().expr_ty(cast_exp); let cast_ty = cx.typeck_results().expr_ty(expr); return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty); } false }
identifier_body
BufferedTokenStream.py
# # [The "BSD license"] # Copyright (c) 2012 Terence Parr # Copyright (c) 2012 Sam Harwell # Copyright (c) 2014 Eric Vergnaud # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. The name of the author may not be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # This implementation of {@link TokenStream} loads tokens from a # {@link TokenSource} on-demand, and places the tokens in a buffer to provide # access to any previous token by index. # # <p> # This token stream ignores the value of {@link Token#getChannel}. If your # parser requires the token stream filter tokens to only those on a particular # channel, such as {@link Token#DEFAULT_CHANNEL} or # {@link Token#HIDDEN_CHANNEL}, use a filtering token stream such a # {@link CommonTokenStream}.</p> from io import StringIO from antlr4.Token import Token from antlr4.error.Errors import IllegalStateException # this is just to keep meaningful parameter types to Parser class TokenStream(object): pass class BufferedTokenStream(TokenStream): def __init__(self, tokenSource): # The {@link TokenSource} from which tokens for this stream are fetched. self.tokenSource = tokenSource # A collection of all tokens fetched from the token source. The list is # considered a complete view of the input once {@link #fetchedEOF} is set # to {@code true}. self.tokens = [] # The index into {@link #tokens} of the current token (next token to # {@link #consume}). {@link #tokens}{@code [}{@link #p}{@code ]} should be # {@link #LT LT(1)}. # # <p>This field is set to -1 when the stream is first constructed or when # {@link #setTokenSource} is called, indicating that the first token has # not yet been fetched from the token source. For additional information, # see the documentation of {@link IntStream} for a description of # Initializing Methods.</p> self.index = -1 # Indicates whether the {@link Token#EOF} token has been fetched from # {@link #tokenSource} and added to {@link #tokens}. This field improves # performance for the following cases: # # <ul> # <li>{@link #consume}: The lookahead check in {@link #consume} to prevent # consuming the EOF symbol is optimized by checking the values of # {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}.</li> # <li>{@link #fetch}: The check to prevent adding multiple EOF symbols into # {@link #tokens} is trivial with this field.</li> # <ul> self.fetchedEOF = False def mark(self): return 0 def release(self, marker): # no resources to release pass def reset(self): self.seek(0) def seek(self, index): self.lazyInit() self.index = self.adjustSeekIndex(index) def get(self, index): self.lazyInit() return self.tokens[index] def consume(self): skipEofCheck = False if self.index >= 0: if self.fetchedEOF: # the last token in tokens is EOF. skip check if p indexes any # fetched token except the last.
else: # no EOF token in tokens. skip check if p indexes a fetched token. skipEofCheck = self.index < len(self.tokens) else: # not yet initialized skipEofCheck = False if not skipEofCheck and self.LA(1) == Token.EOF: raise IllegalStateException("cannot consume EOF") if self.sync(self.index + 1): self.index = self.adjustSeekIndex(self.index + 1) # Make sure index {@code i} in tokens has a token. # # @return {@code true} if a token is located at index {@code i}, otherwise # {@code false}. # @see #get(int i) #/ def sync(self, i): assert i >= 0 n = i - len(self.tokens) + 1 # how many more elements we need? if n > 0 : fetched = self.fetch(n) return fetched >= n return True # Add {@code n} elements to buffer. # # @return The actual number of elements added to the buffer. #/ def fetch(self, n): if self.fetchedEOF: return 0 for i in range(0, n): t = self.tokenSource.nextToken() t.tokenIndex = len(self.tokens) self.tokens.append(t) if t.type==Token.EOF: self.fetchedEOF = True return i + 1 return n # Get all tokens from start..stop inclusively#/ def getTokens(self, start, stop, types=None): if start<0 or stop<0: return None self.lazyInit() subset = [] if stop >= len(self.tokens): stop = len(self.tokens)-1 for i in range(start, stop): t = self.tokens[i] if t.type==Token.EOF: break if types is None or t.type in types: subset.append(t) return subset def LA(self, i): return self.LT(i).type def LB(self, k): if (self.index-k) < 0: return None return self.tokens[self.index-k] def LT(self, k): self.lazyInit() if k==0: return None if k < 0: return self.LB(-k) i = self.index + k - 1 self.sync(i) if i >= len(self.tokens): # return EOF token # EOF must be last token return self.tokens[len(self.tokens)-1] return self.tokens[i] # Allowed derived classes to modify the behavior of operations which change # the current stream position by adjusting the target token index of a seek # operation. The default implementation simply returns {@code i}. If an # exception is thrown in this method, the current stream index should not be # changed. # # <p>For example, {@link CommonTokenStream} overrides this method to ensure that # the seek target is always an on-channel token.</p> # # @param i The target token index. # @return The adjusted target token index. def adjustSeekIndex(self, i): return i def lazyInit(self): if self.index == -1: self.setup() def setup(self): self.sync(0) self.index = self.adjustSeekIndex(0) # Reset this token stream by setting its token source.#/ def setTokenSource(self, tokenSource): self.tokenSource = tokenSource self.tokens = [] self.index = -1 # Given a starting index, return the index of the next token on channel. # Return i if tokens[i] is on channel. Return -1 if there are no tokens # on channel between i and EOF. #/ def nextTokenOnChannel(self, i, channel): self.sync(i) if i>=len(self.tokens): return -1 token = self.tokens[i] while token.channel!=channel: if token.type==Token.EOF: return -1 i += 1 self.sync(i) token = self.tokens[i] return i # Given a starting index, return the index of the previous token on channel. # Return i if tokens[i] is on channel. Return -1 if there are no tokens # on channel between i and 0. def previousTokenOnChannel(self, i, channel): while i>=0 and self.tokens[i].channel!=channel: i -= 1 return i # Collect all tokens on specified channel to the right of # the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or # EOF. If channel is -1, find any non default channel token. def getHiddenTokensToRight(self, tokenIndex, channel=-1): self.lazyInit() if tokenIndex<0 or tokenIndex>=len(self.tokens): raise Exception(str(tokenIndex) + " not in 0.." + str(len(self.tokens)-1)) from antlr4.Lexer import Lexer nextOnChannel = self.nextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL) from_ = tokenIndex+1 # if none onchannel to right, nextOnChannel=-1 so set to = last token to = (len(self.tokens)-1) if nextOnChannel==-1 else nextOnChannel return self.filterForChannel(from_, to, channel) # Collect all tokens on specified channel to the left of # the current token up until we see a token on DEFAULT_TOKEN_CHANNEL. # If channel is -1, find any non default channel token. def getHiddenTokensToLeft(self, tokenIndex, channel=-1): self.lazyInit() if tokenIndex<0 or tokenIndex>=len(self.tokens): raise Exception(str(tokenIndex) + " not in 0.." + str(len(self.tokens)-1)) from antlr4.Lexer import Lexer prevOnChannel = self.previousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT_TOKEN_CHANNEL) if prevOnChannel == tokenIndex - 1: return None # if none on channel to left, prevOnChannel=-1 then from=0 from_ = prevOnChannel+1 to = tokenIndex-1 return self.filterForChannel(from_, to, channel) def filterForChannel(self, left, right, channel): hidden = [] for i in range(left, right+1): t = self.tokens[i] if channel==-1: from antlr4.Lexer import Lexer if t.channel!= Lexer.DEFAULT_TOKEN_CHANNEL: hidden.append(t) elif t.channel==channel: hidden.append(t) if len(hidden)==0: return None return hidden def getSourceName(self): return self.tokenSource.getSourceName() # Get the text of all tokens in this buffer.#/ def getText(self, interval=None): self.lazyInit() self.fill() if interval is None: interval = (0, len(self.tokens)-1) start = interval[0] if isinstance(start, Token): start = start.tokenIndex stop = interval[1] if isinstance(stop, Token): stop = stop.tokenIndex if start is None or stop is None or start<0 or stop<0: return "" if stop >= len(self.tokens): stop = len(self.tokens)-1 with StringIO() as buf: for i in range(start, stop+1): t = self.tokens[i] if t.type==Token.EOF: break buf.write(t.text) return buf.getvalue() # Get all tokens from lexer until EOF#/ def fill(self): self.lazyInit() while self.fetch(1000)==1000: pass
skipEofCheck = self.index < len(self.tokens) - 1
conditional_block
BufferedTokenStream.py
# # [The "BSD license"] # Copyright (c) 2012 Terence Parr # Copyright (c) 2012 Sam Harwell # Copyright (c) 2014 Eric Vergnaud # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. The name of the author may not be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # This implementation of {@link TokenStream} loads tokens from a # {@link TokenSource} on-demand, and places the tokens in a buffer to provide # access to any previous token by index. # # <p> # This token stream ignores the value of {@link Token#getChannel}. If your # parser requires the token stream filter tokens to only those on a particular # channel, such as {@link Token#DEFAULT_CHANNEL} or # {@link Token#HIDDEN_CHANNEL}, use a filtering token stream such a # {@link CommonTokenStream}.</p> from io import StringIO from antlr4.Token import Token from antlr4.error.Errors import IllegalStateException # this is just to keep meaningful parameter types to Parser class TokenStream(object): pass class BufferedTokenStream(TokenStream): def __init__(self, tokenSource): # The {@link TokenSource} from which tokens for this stream are fetched. self.tokenSource = tokenSource # A collection of all tokens fetched from the token source. The list is # considered a complete view of the input once {@link #fetchedEOF} is set # to {@code true}. self.tokens = [] # The index into {@link #tokens} of the current token (next token to # {@link #consume}). {@link #tokens}{@code [}{@link #p}{@code ]} should be # {@link #LT LT(1)}. # # <p>This field is set to -1 when the stream is first constructed or when # {@link #setTokenSource} is called, indicating that the first token has # not yet been fetched from the token source. For additional information, # see the documentation of {@link IntStream} for a description of # Initializing Methods.</p> self.index = -1 # Indicates whether the {@link Token#EOF} token has been fetched from # {@link #tokenSource} and added to {@link #tokens}. This field improves # performance for the following cases: # # <ul> # <li>{@link #consume}: The lookahead check in {@link #consume} to prevent # consuming the EOF symbol is optimized by checking the values of # {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}.</li> # <li>{@link #fetch}: The check to prevent adding multiple EOF symbols into # {@link #tokens} is trivial with this field.</li> # <ul> self.fetchedEOF = False def mark(self): return 0 def release(self, marker): # no resources to release pass def reset(self): self.seek(0) def seek(self, index): self.lazyInit() self.index = self.adjustSeekIndex(index) def get(self, index): self.lazyInit() return self.tokens[index] def consume(self): skipEofCheck = False if self.index >= 0: if self.fetchedEOF: # the last token in tokens is EOF. skip check if p indexes any # fetched token except the last. skipEofCheck = self.index < len(self.tokens) - 1 else: # no EOF token in tokens. skip check if p indexes a fetched token. skipEofCheck = self.index < len(self.tokens) else: # not yet initialized skipEofCheck = False if not skipEofCheck and self.LA(1) == Token.EOF: raise IllegalStateException("cannot consume EOF") if self.sync(self.index + 1): self.index = self.adjustSeekIndex(self.index + 1) # Make sure index {@code i} in tokens has a token. # # @return {@code true} if a token is located at index {@code i}, otherwise # {@code false}. # @see #get(int i) #/ def sync(self, i): assert i >= 0 n = i - len(self.tokens) + 1 # how many more elements we need? if n > 0 : fetched = self.fetch(n) return fetched >= n return True # Add {@code n} elements to buffer. # # @return The actual number of elements added to the buffer. #/ def fetch(self, n): if self.fetchedEOF: return 0 for i in range(0, n): t = self.tokenSource.nextToken() t.tokenIndex = len(self.tokens) self.tokens.append(t) if t.type==Token.EOF: self.fetchedEOF = True return i + 1 return n # Get all tokens from start..stop inclusively#/ def getTokens(self, start, stop, types=None): if start<0 or stop<0: return None self.lazyInit() subset = [] if stop >= len(self.tokens): stop = len(self.tokens)-1 for i in range(start, stop): t = self.tokens[i] if t.type==Token.EOF: break if types is None or t.type in types: subset.append(t) return subset def LA(self, i): return self.LT(i).type def LB(self, k): if (self.index-k) < 0: return None return self.tokens[self.index-k] def LT(self, k): self.lazyInit() if k==0: return None if k < 0: return self.LB(-k) i = self.index + k - 1 self.sync(i) if i >= len(self.tokens): # return EOF token # EOF must be last token return self.tokens[len(self.tokens)-1] return self.tokens[i] # Allowed derived classes to modify the behavior of operations which change # the current stream position by adjusting the target token index of a seek # operation. The default implementation simply returns {@code i}. If an # exception is thrown in this method, the current stream index should not be # changed. # # <p>For example, {@link CommonTokenStream} overrides this method to ensure that # the seek target is always an on-channel token.</p> # # @param i The target token index. # @return The adjusted target token index. def adjustSeekIndex(self, i): return i def lazyInit(self): if self.index == -1: self.setup() def setup(self): self.sync(0) self.index = self.adjustSeekIndex(0) # Reset this token stream by setting its token source.#/ def setTokenSource(self, tokenSource): self.tokenSource = tokenSource self.tokens = [] self.index = -1 # Given a starting index, return the index of the next token on channel. # Return i if tokens[i] is on channel. Return -1 if there are no tokens # on channel between i and EOF. #/ def nextTokenOnChannel(self, i, channel): self.sync(i) if i>=len(self.tokens): return -1 token = self.tokens[i] while token.channel!=channel: if token.type==Token.EOF: return -1 i += 1 self.sync(i) token = self.tokens[i] return i # Given a starting index, return the index of the previous token on channel. # Return i if tokens[i] is on channel. Return -1 if there are no tokens # on channel between i and 0. def previousTokenOnChannel(self, i, channel): while i>=0 and self.tokens[i].channel!=channel: i -= 1 return i # Collect all tokens on specified channel to the right of # the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or # EOF. If channel is -1, find any non default channel token. def getHiddenTokensToRight(self, tokenIndex, channel=-1): self.lazyInit() if tokenIndex<0 or tokenIndex>=len(self.tokens): raise Exception(str(tokenIndex) + " not in 0.." + str(len(self.tokens)-1)) from antlr4.Lexer import Lexer nextOnChannel = self.nextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL) from_ = tokenIndex+1 # if none onchannel to right, nextOnChannel=-1 so set to = last token to = (len(self.tokens)-1) if nextOnChannel==-1 else nextOnChannel return self.filterForChannel(from_, to, channel) # Collect all tokens on specified channel to the left of # the current token up until we see a token on DEFAULT_TOKEN_CHANNEL. # If channel is -1, find any non default channel token. def
(self, tokenIndex, channel=-1): self.lazyInit() if tokenIndex<0 or tokenIndex>=len(self.tokens): raise Exception(str(tokenIndex) + " not in 0.." + str(len(self.tokens)-1)) from antlr4.Lexer import Lexer prevOnChannel = self.previousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT_TOKEN_CHANNEL) if prevOnChannel == tokenIndex - 1: return None # if none on channel to left, prevOnChannel=-1 then from=0 from_ = prevOnChannel+1 to = tokenIndex-1 return self.filterForChannel(from_, to, channel) def filterForChannel(self, left, right, channel): hidden = [] for i in range(left, right+1): t = self.tokens[i] if channel==-1: from antlr4.Lexer import Lexer if t.channel!= Lexer.DEFAULT_TOKEN_CHANNEL: hidden.append(t) elif t.channel==channel: hidden.append(t) if len(hidden)==0: return None return hidden def getSourceName(self): return self.tokenSource.getSourceName() # Get the text of all tokens in this buffer.#/ def getText(self, interval=None): self.lazyInit() self.fill() if interval is None: interval = (0, len(self.tokens)-1) start = interval[0] if isinstance(start, Token): start = start.tokenIndex stop = interval[1] if isinstance(stop, Token): stop = stop.tokenIndex if start is None or stop is None or start<0 or stop<0: return "" if stop >= len(self.tokens): stop = len(self.tokens)-1 with StringIO() as buf: for i in range(start, stop+1): t = self.tokens[i] if t.type==Token.EOF: break buf.write(t.text) return buf.getvalue() # Get all tokens from lexer until EOF#/ def fill(self): self.lazyInit() while self.fetch(1000)==1000: pass
getHiddenTokensToLeft
identifier_name
BufferedTokenStream.py
# # [The "BSD license"] # Copyright (c) 2012 Terence Parr # Copyright (c) 2012 Sam Harwell # Copyright (c) 2014 Eric Vergnaud # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. The name of the author may not be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # This implementation of {@link TokenStream} loads tokens from a # {@link TokenSource} on-demand, and places the tokens in a buffer to provide # access to any previous token by index. # # <p> # This token stream ignores the value of {@link Token#getChannel}. If your # parser requires the token stream filter tokens to only those on a particular # channel, such as {@link Token#DEFAULT_CHANNEL} or # {@link Token#HIDDEN_CHANNEL}, use a filtering token stream such a # {@link CommonTokenStream}.</p> from io import StringIO from antlr4.Token import Token from antlr4.error.Errors import IllegalStateException # this is just to keep meaningful parameter types to Parser class TokenStream(object): pass class BufferedTokenStream(TokenStream): def __init__(self, tokenSource): # The {@link TokenSource} from which tokens for this stream are fetched. self.tokenSource = tokenSource # A collection of all tokens fetched from the token source. The list is # considered a complete view of the input once {@link #fetchedEOF} is set # to {@code true}. self.tokens = [] # The index into {@link #tokens} of the current token (next token to # {@link #consume}). {@link #tokens}{@code [}{@link #p}{@code ]} should be # {@link #LT LT(1)}. # # <p>This field is set to -1 when the stream is first constructed or when # {@link #setTokenSource} is called, indicating that the first token has # not yet been fetched from the token source. For additional information, # see the documentation of {@link IntStream} for a description of # Initializing Methods.</p> self.index = -1 # Indicates whether the {@link Token#EOF} token has been fetched from # {@link #tokenSource} and added to {@link #tokens}. This field improves # performance for the following cases: # # <ul> # <li>{@link #consume}: The lookahead check in {@link #consume} to prevent # consuming the EOF symbol is optimized by checking the values of # {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}.</li> # <li>{@link #fetch}: The check to prevent adding multiple EOF symbols into # {@link #tokens} is trivial with this field.</li> # <ul> self.fetchedEOF = False def mark(self): return 0 def release(self, marker): # no resources to release pass def reset(self): self.seek(0) def seek(self, index): self.lazyInit() self.index = self.adjustSeekIndex(index) def get(self, index): self.lazyInit() return self.tokens[index] def consume(self): skipEofCheck = False if self.index >= 0: if self.fetchedEOF: # the last token in tokens is EOF. skip check if p indexes any # fetched token except the last. skipEofCheck = self.index < len(self.tokens) - 1 else: # no EOF token in tokens. skip check if p indexes a fetched token. skipEofCheck = self.index < len(self.tokens) else: # not yet initialized skipEofCheck = False if not skipEofCheck and self.LA(1) == Token.EOF: raise IllegalStateException("cannot consume EOF") if self.sync(self.index + 1): self.index = self.adjustSeekIndex(self.index + 1) # Make sure index {@code i} in tokens has a token. # # @return {@code true} if a token is located at index {@code i}, otherwise # {@code false}. # @see #get(int i) #/ def sync(self, i): assert i >= 0 n = i - len(self.tokens) + 1 # how many more elements we need? if n > 0 : fetched = self.fetch(n) return fetched >= n return True # Add {@code n} elements to buffer. # # @return The actual number of elements added to the buffer. #/ def fetch(self, n): if self.fetchedEOF: return 0 for i in range(0, n): t = self.tokenSource.nextToken() t.tokenIndex = len(self.tokens) self.tokens.append(t) if t.type==Token.EOF: self.fetchedEOF = True return i + 1 return n # Get all tokens from start..stop inclusively#/ def getTokens(self, start, stop, types=None): if start<0 or stop<0: return None self.lazyInit() subset = [] if stop >= len(self.tokens): stop = len(self.tokens)-1 for i in range(start, stop): t = self.tokens[i] if t.type==Token.EOF: break if types is None or t.type in types: subset.append(t) return subset def LA(self, i): return self.LT(i).type def LB(self, k): if (self.index-k) < 0: return None return self.tokens[self.index-k] def LT(self, k): self.lazyInit() if k==0: return None if k < 0: return self.LB(-k) i = self.index + k - 1 self.sync(i) if i >= len(self.tokens): # return EOF token # EOF must be last token return self.tokens[len(self.tokens)-1] return self.tokens[i] # Allowed derived classes to modify the behavior of operations which change # the current stream position by adjusting the target token index of a seek # operation. The default implementation simply returns {@code i}. If an # exception is thrown in this method, the current stream index should not be # changed. # # <p>For example, {@link CommonTokenStream} overrides this method to ensure that # the seek target is always an on-channel token.</p> # # @param i The target token index. # @return The adjusted target token index. def adjustSeekIndex(self, i): return i def lazyInit(self): if self.index == -1: self.setup() def setup(self): self.sync(0) self.index = self.adjustSeekIndex(0) # Reset this token stream by setting its token source.#/ def setTokenSource(self, tokenSource): self.tokenSource = tokenSource
self.index = -1 # Given a starting index, return the index of the next token on channel. # Return i if tokens[i] is on channel. Return -1 if there are no tokens # on channel between i and EOF. #/ def nextTokenOnChannel(self, i, channel): self.sync(i) if i>=len(self.tokens): return -1 token = self.tokens[i] while token.channel!=channel: if token.type==Token.EOF: return -1 i += 1 self.sync(i) token = self.tokens[i] return i # Given a starting index, return the index of the previous token on channel. # Return i if tokens[i] is on channel. Return -1 if there are no tokens # on channel between i and 0. def previousTokenOnChannel(self, i, channel): while i>=0 and self.tokens[i].channel!=channel: i -= 1 return i # Collect all tokens on specified channel to the right of # the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or # EOF. If channel is -1, find any non default channel token. def getHiddenTokensToRight(self, tokenIndex, channel=-1): self.lazyInit() if tokenIndex<0 or tokenIndex>=len(self.tokens): raise Exception(str(tokenIndex) + " not in 0.." + str(len(self.tokens)-1)) from antlr4.Lexer import Lexer nextOnChannel = self.nextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL) from_ = tokenIndex+1 # if none onchannel to right, nextOnChannel=-1 so set to = last token to = (len(self.tokens)-1) if nextOnChannel==-1 else nextOnChannel return self.filterForChannel(from_, to, channel) # Collect all tokens on specified channel to the left of # the current token up until we see a token on DEFAULT_TOKEN_CHANNEL. # If channel is -1, find any non default channel token. def getHiddenTokensToLeft(self, tokenIndex, channel=-1): self.lazyInit() if tokenIndex<0 or tokenIndex>=len(self.tokens): raise Exception(str(tokenIndex) + " not in 0.." + str(len(self.tokens)-1)) from antlr4.Lexer import Lexer prevOnChannel = self.previousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT_TOKEN_CHANNEL) if prevOnChannel == tokenIndex - 1: return None # if none on channel to left, prevOnChannel=-1 then from=0 from_ = prevOnChannel+1 to = tokenIndex-1 return self.filterForChannel(from_, to, channel) def filterForChannel(self, left, right, channel): hidden = [] for i in range(left, right+1): t = self.tokens[i] if channel==-1: from antlr4.Lexer import Lexer if t.channel!= Lexer.DEFAULT_TOKEN_CHANNEL: hidden.append(t) elif t.channel==channel: hidden.append(t) if len(hidden)==0: return None return hidden def getSourceName(self): return self.tokenSource.getSourceName() # Get the text of all tokens in this buffer.#/ def getText(self, interval=None): self.lazyInit() self.fill() if interval is None: interval = (0, len(self.tokens)-1) start = interval[0] if isinstance(start, Token): start = start.tokenIndex stop = interval[1] if isinstance(stop, Token): stop = stop.tokenIndex if start is None or stop is None or start<0 or stop<0: return "" if stop >= len(self.tokens): stop = len(self.tokens)-1 with StringIO() as buf: for i in range(start, stop+1): t = self.tokens[i] if t.type==Token.EOF: break buf.write(t.text) return buf.getvalue() # Get all tokens from lexer until EOF#/ def fill(self): self.lazyInit() while self.fetch(1000)==1000: pass
self.tokens = []
random_line_split
BufferedTokenStream.py
# # [The "BSD license"] # Copyright (c) 2012 Terence Parr # Copyright (c) 2012 Sam Harwell # Copyright (c) 2014 Eric Vergnaud # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. The name of the author may not be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # This implementation of {@link TokenStream} loads tokens from a # {@link TokenSource} on-demand, and places the tokens in a buffer to provide # access to any previous token by index. # # <p> # This token stream ignores the value of {@link Token#getChannel}. If your # parser requires the token stream filter tokens to only those on a particular # channel, such as {@link Token#DEFAULT_CHANNEL} or # {@link Token#HIDDEN_CHANNEL}, use a filtering token stream such a # {@link CommonTokenStream}.</p> from io import StringIO from antlr4.Token import Token from antlr4.error.Errors import IllegalStateException # this is just to keep meaningful parameter types to Parser class TokenStream(object):
class BufferedTokenStream(TokenStream): def __init__(self, tokenSource): # The {@link TokenSource} from which tokens for this stream are fetched. self.tokenSource = tokenSource # A collection of all tokens fetched from the token source. The list is # considered a complete view of the input once {@link #fetchedEOF} is set # to {@code true}. self.tokens = [] # The index into {@link #tokens} of the current token (next token to # {@link #consume}). {@link #tokens}{@code [}{@link #p}{@code ]} should be # {@link #LT LT(1)}. # # <p>This field is set to -1 when the stream is first constructed or when # {@link #setTokenSource} is called, indicating that the first token has # not yet been fetched from the token source. For additional information, # see the documentation of {@link IntStream} for a description of # Initializing Methods.</p> self.index = -1 # Indicates whether the {@link Token#EOF} token has been fetched from # {@link #tokenSource} and added to {@link #tokens}. This field improves # performance for the following cases: # # <ul> # <li>{@link #consume}: The lookahead check in {@link #consume} to prevent # consuming the EOF symbol is optimized by checking the values of # {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}.</li> # <li>{@link #fetch}: The check to prevent adding multiple EOF symbols into # {@link #tokens} is trivial with this field.</li> # <ul> self.fetchedEOF = False def mark(self): return 0 def release(self, marker): # no resources to release pass def reset(self): self.seek(0) def seek(self, index): self.lazyInit() self.index = self.adjustSeekIndex(index) def get(self, index): self.lazyInit() return self.tokens[index] def consume(self): skipEofCheck = False if self.index >= 0: if self.fetchedEOF: # the last token in tokens is EOF. skip check if p indexes any # fetched token except the last. skipEofCheck = self.index < len(self.tokens) - 1 else: # no EOF token in tokens. skip check if p indexes a fetched token. skipEofCheck = self.index < len(self.tokens) else: # not yet initialized skipEofCheck = False if not skipEofCheck and self.LA(1) == Token.EOF: raise IllegalStateException("cannot consume EOF") if self.sync(self.index + 1): self.index = self.adjustSeekIndex(self.index + 1) # Make sure index {@code i} in tokens has a token. # # @return {@code true} if a token is located at index {@code i}, otherwise # {@code false}. # @see #get(int i) #/ def sync(self, i): assert i >= 0 n = i - len(self.tokens) + 1 # how many more elements we need? if n > 0 : fetched = self.fetch(n) return fetched >= n return True # Add {@code n} elements to buffer. # # @return The actual number of elements added to the buffer. #/ def fetch(self, n): if self.fetchedEOF: return 0 for i in range(0, n): t = self.tokenSource.nextToken() t.tokenIndex = len(self.tokens) self.tokens.append(t) if t.type==Token.EOF: self.fetchedEOF = True return i + 1 return n # Get all tokens from start..stop inclusively#/ def getTokens(self, start, stop, types=None): if start<0 or stop<0: return None self.lazyInit() subset = [] if stop >= len(self.tokens): stop = len(self.tokens)-1 for i in range(start, stop): t = self.tokens[i] if t.type==Token.EOF: break if types is None or t.type in types: subset.append(t) return subset def LA(self, i): return self.LT(i).type def LB(self, k): if (self.index-k) < 0: return None return self.tokens[self.index-k] def LT(self, k): self.lazyInit() if k==0: return None if k < 0: return self.LB(-k) i = self.index + k - 1 self.sync(i) if i >= len(self.tokens): # return EOF token # EOF must be last token return self.tokens[len(self.tokens)-1] return self.tokens[i] # Allowed derived classes to modify the behavior of operations which change # the current stream position by adjusting the target token index of a seek # operation. The default implementation simply returns {@code i}. If an # exception is thrown in this method, the current stream index should not be # changed. # # <p>For example, {@link CommonTokenStream} overrides this method to ensure that # the seek target is always an on-channel token.</p> # # @param i The target token index. # @return The adjusted target token index. def adjustSeekIndex(self, i): return i def lazyInit(self): if self.index == -1: self.setup() def setup(self): self.sync(0) self.index = self.adjustSeekIndex(0) # Reset this token stream by setting its token source.#/ def setTokenSource(self, tokenSource): self.tokenSource = tokenSource self.tokens = [] self.index = -1 # Given a starting index, return the index of the next token on channel. # Return i if tokens[i] is on channel. Return -1 if there are no tokens # on channel between i and EOF. #/ def nextTokenOnChannel(self, i, channel): self.sync(i) if i>=len(self.tokens): return -1 token = self.tokens[i] while token.channel!=channel: if token.type==Token.EOF: return -1 i += 1 self.sync(i) token = self.tokens[i] return i # Given a starting index, return the index of the previous token on channel. # Return i if tokens[i] is on channel. Return -1 if there are no tokens # on channel between i and 0. def previousTokenOnChannel(self, i, channel): while i>=0 and self.tokens[i].channel!=channel: i -= 1 return i # Collect all tokens on specified channel to the right of # the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or # EOF. If channel is -1, find any non default channel token. def getHiddenTokensToRight(self, tokenIndex, channel=-1): self.lazyInit() if tokenIndex<0 or tokenIndex>=len(self.tokens): raise Exception(str(tokenIndex) + " not in 0.." + str(len(self.tokens)-1)) from antlr4.Lexer import Lexer nextOnChannel = self.nextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL) from_ = tokenIndex+1 # if none onchannel to right, nextOnChannel=-1 so set to = last token to = (len(self.tokens)-1) if nextOnChannel==-1 else nextOnChannel return self.filterForChannel(from_, to, channel) # Collect all tokens on specified channel to the left of # the current token up until we see a token on DEFAULT_TOKEN_CHANNEL. # If channel is -1, find any non default channel token. def getHiddenTokensToLeft(self, tokenIndex, channel=-1): self.lazyInit() if tokenIndex<0 or tokenIndex>=len(self.tokens): raise Exception(str(tokenIndex) + " not in 0.." + str(len(self.tokens)-1)) from antlr4.Lexer import Lexer prevOnChannel = self.previousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT_TOKEN_CHANNEL) if prevOnChannel == tokenIndex - 1: return None # if none on channel to left, prevOnChannel=-1 then from=0 from_ = prevOnChannel+1 to = tokenIndex-1 return self.filterForChannel(from_, to, channel) def filterForChannel(self, left, right, channel): hidden = [] for i in range(left, right+1): t = self.tokens[i] if channel==-1: from antlr4.Lexer import Lexer if t.channel!= Lexer.DEFAULT_TOKEN_CHANNEL: hidden.append(t) elif t.channel==channel: hidden.append(t) if len(hidden)==0: return None return hidden def getSourceName(self): return self.tokenSource.getSourceName() # Get the text of all tokens in this buffer.#/ def getText(self, interval=None): self.lazyInit() self.fill() if interval is None: interval = (0, len(self.tokens)-1) start = interval[0] if isinstance(start, Token): start = start.tokenIndex stop = interval[1] if isinstance(stop, Token): stop = stop.tokenIndex if start is None or stop is None or start<0 or stop<0: return "" if stop >= len(self.tokens): stop = len(self.tokens)-1 with StringIO() as buf: for i in range(start, stop+1): t = self.tokens[i] if t.type==Token.EOF: break buf.write(t.text) return buf.getvalue() # Get all tokens from lexer until EOF#/ def fill(self): self.lazyInit() while self.fetch(1000)==1000: pass
pass
identifier_body
myApp.js
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ var CircleSprite = cc.Sprite.extend({ _degree:0, ctor:function () { this._super(); }, draw:function () { cc.drawingUtil.setDrawColor4B(255,255,255,255); if (this._degree < 0) this._degree = 360; cc.drawingUtil.drawCircle(cc.PointZero(), 30, cc.DEGREES_TO_RADIANS(this._degree), 60, true); }, myUpdate:function (dt) { this._degree -= 6; } }); var Helloworld = cc.Layer.extend({ isMouseDown:false, helloImg:null, helloLabel:null, circle:null, sprite:null, init:function () { var selfPointer = this; ////////////////////////////// // 1. super init first this._super(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // ask director the window size var size = cc.Director.getInstance().getWinSize(); // add a "close" icon to exit the progress. it's an autorelease object var closeItem = cc.MenuItemImage.create( "res/CloseNormal.png", "res/CloseSelected.png", function () { history.go(-1); },this); closeItem.setAnchorPoint(cc.p(0.5, 0.5)); var menu = cc.Menu.create(closeItem); menu.setPosition(cc.PointZero()); this.addChild(menu, 1); closeItem.setPosition(cc.p(size.width - 20, 20)); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label this.helloLabel = cc.LabelTTF.create("Hello World", "Arial", 38); // position the label on the center of the screen this.helloLabel.setPosition(cc.p(size.width / 2, 0)); // add the label as a child to this layer this.addChild(this.helloLabel, 5); var lazyLayer = cc.Layer.create(); this.addChild(lazyLayer); // add "HelloWorld" splash screen" this.sprite = cc.Sprite.create("res/HelloWorld.png"); this.sprite.setPosition(cc.p(size.width / 2, size.height / 2)); this.sprite.setScale(0.5); this.sprite.setRotation(180); lazyLayer.addChild(this.sprite, 0); var rotateToA = cc.RotateTo.create(2, 0); var scaleToA = cc.ScaleTo.create(2, 1, 1); this.sprite.runAction(cc.Sequence.create(rotateToA, scaleToA)); this.circle = new CircleSprite(); this.circle.setPosition(cc.p(40, size.height - 60)); this.addChild(this.circle, 2); this.circle.schedule(this.circle.myUpdate, 1 / 60); this.helloLabel.runAction(cc.Spawn.create(cc.MoveBy.create(2.5, cc.p(0, size.height - 40)),cc.TintTo.create(2.5,255,125,0))); this.setTouchEnabled(true); return true; }, // a selector callback menuCloseCallback:function (sender) { cc.Director.getInstance().end(); }, onTouchesBegan:function (touches, event) { this.isMouseDown = true; }, onTouchesMoved:function (touches, event) { if (this.isMouseDown) { if (touches) { //this.circle.setPosition(cc.p(touches[0].getLocation().x, touches[0].getLocation().y)); } } }, onTouchesEnded:function (touches, event) { this.isMouseDown = false; }, onTouchesCancelled:function (touches, event) { console.log("onTouchesCancelled"); }
}); var HelloWorldScene = cc.Scene.extend({ onEnter:function () { this._super(); var layer = new Helloworld(); layer.init(); this.addChild(layer); } });
random_line_split
myApp.js
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ var CircleSprite = cc.Sprite.extend({ _degree:0, ctor:function () { this._super(); }, draw:function () { cc.drawingUtil.setDrawColor4B(255,255,255,255); if (this._degree < 0) this._degree = 360; cc.drawingUtil.drawCircle(cc.PointZero(), 30, cc.DEGREES_TO_RADIANS(this._degree), 60, true); }, myUpdate:function (dt) { this._degree -= 6; } }); var Helloworld = cc.Layer.extend({ isMouseDown:false, helloImg:null, helloLabel:null, circle:null, sprite:null, init:function () { var selfPointer = this; ////////////////////////////// // 1. super init first this._super(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // ask director the window size var size = cc.Director.getInstance().getWinSize(); // add a "close" icon to exit the progress. it's an autorelease object var closeItem = cc.MenuItemImage.create( "res/CloseNormal.png", "res/CloseSelected.png", function () { history.go(-1); },this); closeItem.setAnchorPoint(cc.p(0.5, 0.5)); var menu = cc.Menu.create(closeItem); menu.setPosition(cc.PointZero()); this.addChild(menu, 1); closeItem.setPosition(cc.p(size.width - 20, 20)); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label this.helloLabel = cc.LabelTTF.create("Hello World", "Arial", 38); // position the label on the center of the screen this.helloLabel.setPosition(cc.p(size.width / 2, 0)); // add the label as a child to this layer this.addChild(this.helloLabel, 5); var lazyLayer = cc.Layer.create(); this.addChild(lazyLayer); // add "HelloWorld" splash screen" this.sprite = cc.Sprite.create("res/HelloWorld.png"); this.sprite.setPosition(cc.p(size.width / 2, size.height / 2)); this.sprite.setScale(0.5); this.sprite.setRotation(180); lazyLayer.addChild(this.sprite, 0); var rotateToA = cc.RotateTo.create(2, 0); var scaleToA = cc.ScaleTo.create(2, 1, 1); this.sprite.runAction(cc.Sequence.create(rotateToA, scaleToA)); this.circle = new CircleSprite(); this.circle.setPosition(cc.p(40, size.height - 60)); this.addChild(this.circle, 2); this.circle.schedule(this.circle.myUpdate, 1 / 60); this.helloLabel.runAction(cc.Spawn.create(cc.MoveBy.create(2.5, cc.p(0, size.height - 40)),cc.TintTo.create(2.5,255,125,0))); this.setTouchEnabled(true); return true; }, // a selector callback menuCloseCallback:function (sender) { cc.Director.getInstance().end(); }, onTouchesBegan:function (touches, event) { this.isMouseDown = true; }, onTouchesMoved:function (touches, event) { if (this.isMouseDown) { if (touches)
} }, onTouchesEnded:function (touches, event) { this.isMouseDown = false; }, onTouchesCancelled:function (touches, event) { console.log("onTouchesCancelled"); } }); var HelloWorldScene = cc.Scene.extend({ onEnter:function () { this._super(); var layer = new Helloworld(); layer.init(); this.addChild(layer); } });
{ //this.circle.setPosition(cc.p(touches[0].getLocation().x, touches[0].getLocation().y)); }
conditional_block
api.ts
import * as firebase from "firebase"; import fetch from "isomorphic-fetch"; import * as jwt from "jsonwebtoken"; import ClientOAuth2 from "client-oauth2"; import fakeOfferingData from "./data/offering-data.json"; import fakeClassData from "./data/small-class-data.json"; import { parseUrl, validFsId, urlParam, urlHashParam } from "./util/misc"; import { getActivityStudentFeedbackKey } from "./util/activity-feedback-helper"; import { getFirebaseAppName, signInWithToken } from "./db"; const PORTAL_AUTH_PATH = "/auth/oauth_authorize"; let accessToken: string | null = null; const FAKE_FIRESTORE_JWT = "fake firestore JWT"; export interface ILTIPartial { platformId: string; // portal platformUserId: string; contextId: string; // class hash resourceLinkId: string; // offering ID } export interface IStateAnswer { questionId: string; platformUserId: string; id: string; } export interface IStateReportPartial extends ILTIPartial { answers: {[key: string]: IStateAnswer}; sourceKey: string; } export interface IPortalRawData extends ILTIPartial{ offering: { id: number; activity_url: string; rubric_url: string; }; classInfo: { id: number; name: string; students: IStudentRawData[]; }; userType: "teacher" | "learner"; sourceKey: string; userId: string; } export interface IStudentRawData { first_name: string; last_name: string; user_id: string; } export interface IResponse { url?: string; status: number; statusText: string; } export interface IFirebaseJWT { claims: { user_type: "teacher" | "learner"; platform_id: string; platform_user_id: number; user_id: string; }; } // extract the hostname from the url export const makeSourceKey = (url: string | null) => { return url ? parseUrl(url.toLowerCase()).hostname : ""; }; export const getSourceKey = (url: string): string => { const sourceKeyParam = urlParam("sourceKey"); return sourceKeyParam || makeSourceKey(url); }; // FIXME: If the user isn't logged in, and then they log in with a user that // isn't the student being reported on then just a blank screen is shown export const authorizeInPortal = (portalUrl: string, oauthClientName: string, state: string) => { const portalAuth = new ClientOAuth2({ clientId: oauthClientName, redirectUri: window.location.origin + window.location.pathname, authorizationUri: `${portalUrl}${PORTAL_AUTH_PATH}`, state }); // Redirect window.location.assign(portalAuth.token.getUri()); }; // Returns true if it is redirecting export const initializeAuthorization = () => { const state = urlHashParam("state"); accessToken = urlHashParam("access_token"); if (accessToken && state) { const savedParamString = sessionStorage.getItem(state); window.history.pushState(null, "Portal Report", savedParamString); } else { const authDomain = urlParam("auth-domain"); // Portal has to have AuthClient configured with this clientId. // The AuthClient has to have: // - redirect URLs of each branch being tested // - "client type" needs to be configured as 'public', to allow browser requests const oauthClientName = "portal-report"; if (authDomain) { const key = Math.random().toString(36).substring(2,15); sessionStorage.setItem(key, window.location.search); authorizeInPortal(authDomain, oauthClientName, key); return true; } } return false; }; const getPortalBaseUrl = () => { const portalUrl = urlParam("class") || urlParam("offering"); if (!portalUrl) { return null; } const { hostname, protocol } = parseUrl(portalUrl); return `${protocol}//${hostname}`; }; export const getPortalFirebaseJWTUrl = (classHash: string, resourceLinkId: string | null, targetUserId: string | null, firebaseApp: string | undefined ) => { if(!firebaseApp){ firebaseApp = getFirebaseAppName(); } const baseUrl = getPortalBaseUrl(); if (!baseUrl)
const resourceLinkParam = resourceLinkId ? `&resource_link_id=${resourceLinkId}` : ""; const targetUserParam = targetUserId ? `&target_user_id=${targetUserId}` : ""; return `${baseUrl}/api/v1/jwt/firebase?firebase_app=${firebaseApp}&class_hash=${classHash}${resourceLinkParam}${targetUserParam}`; }; export function getAuthHeader() { if (urlParam("token")) { return `Bearer ${urlParam("token")}`; } if (accessToken) { return `Bearer ${accessToken}`; } throw new APIError("No token available to set auth header", { status: 0, statusText: "No token available to set auth header" }); } export function fetchOfferingData() { const offeringUrl = urlParam("offering"); if (offeringUrl) { return fetch(offeringUrl, {headers: {Authorization: getAuthHeader()}}) .then(checkStatus) .then((response: Body) => response.json()); } else { return new Promise(resolve => setTimeout(() => resolve(fakeOfferingData), 250)); } } export function fetchClassData() { const classInfoUrl = urlParam("class"); if (classInfoUrl) { return fetch(classInfoUrl, {headers: {Authorization: getAuthHeader()}}) .then(checkStatus) .then(response => response.json()); } else { return new Promise(resolve => setTimeout(() => resolve(fakeClassData), 250)); } } export function fetchFirestoreJWT(classHash: string, resourceLinkId: string | null = null, targetUserId: string | null = null, firebaseApp?: string): Promise<{token: string}> { const firestoreJWTUrl = getPortalFirebaseJWTUrl(classHash, resourceLinkId, targetUserId, firebaseApp ); if (firestoreJWTUrl) { return fetch(firestoreJWTUrl, {headers: {Authorization: getAuthHeader()}}) .then(checkStatus) .then(response => response.json()); } else { return new Promise(resolve => setTimeout(() => resolve({token: FAKE_FIRESTORE_JWT}), 250)); } } export function fetchFirestoreJWTWithDefaultParams(firebaseApp?: string): Promise<{token: string}> { return Promise.all([fetchOfferingData(), fetchClassData()]) .then(([offeringData, classData]) => { const resourceLinkId = offeringData.id.toString(); const studentId = urlParam("studentId"); // only pass resourceLinkId if there is a studentId // This could be a teacher or researcher viewing the report of a student // The studentId is sent in the firestore JWT request as the target_user_id return fetchFirestoreJWT(classData.class_hash, studentId ? resourceLinkId : null, studentId, firebaseApp); }); } export function authFirestore(rawFirestoreJWT: string) { const authResult = signInWithToken(rawFirestoreJWT) as Promise<firebase.auth.UserCredential | void>; return authResult.catch(err => { console.error("Firebase auth failed", err); throw new APIError("Firebase failed", { status: 401, // this will render nice error message that mentions authorization problems statusText: "Firebase authorization failed" }); }); } function fakeUserType(): "teacher" | "learner" { const userType = urlParam("fakeUserType"); if (userType === "teacher" || userType === "learner") { return userType; } return "teacher"; } function fakeUserId() { const userType = urlParam("fakeUserType") || "learner"; return `${userType}@fake.portal`; } export function fetchPortalDataAndAuthFirestore(): Promise<IPortalRawData> { const offeringPromise = fetchOfferingData(); const classPromise = fetchClassData(); return Promise.all([offeringPromise, classPromise]).then(([offeringData, classData]: [any, any]) => { const resourceLinkId = offeringData.id.toString(); const studentId = urlParam("studentId"); // only pass resourceLinkId if there is a studentId // This could be a teacher or researcher viewing the report of a student // The studentId is sent in the firestore JWT request as the target_user_id const firestoreJWTPromise = fetchFirestoreJWT(classData.class_hash, studentId ? resourceLinkId : null, studentId); return firestoreJWTPromise.then((result: any) => { const rawFirestoreJWT = result.token; if (rawFirestoreJWT !== FAKE_FIRESTORE_JWT) { // We're not using fake data. const decodedFirebaseJWT = jwt.decode(rawFirestoreJWT); if (!decodedFirebaseJWT || typeof decodedFirebaseJWT === "string") { throw new APIError("Firebase JWT parsing error", { status: 500, statusText: "Firebase JWT parsing error" }); } const verifiedFirebaseJWT = decodedFirebaseJWT as IFirebaseJWT; return authFirestore(rawFirestoreJWT).then(() => ({ offering: offeringData, resourceLinkId, classInfo: classData, userType: verifiedFirebaseJWT.claims.user_type, platformId: verifiedFirebaseJWT.claims.platform_id, platformUserId: verifiedFirebaseJWT.claims.platform_user_id.toString(), contextId: classData.class_hash, sourceKey: getSourceKey(offeringData.activity_url), userId: verifiedFirebaseJWT.claims.user_id }) ); } else { // We're using fake data, including fake JWT. return { offering: offeringData, resourceLinkId: offeringData.id.toString(), classInfo: classData, userType: fakeUserType(), platformId: "https://fake.portal", platformUserId: urlParam("fakePlatformUserId") || "1", contextId: classData.class_hash, // In most cases when using fake data the sourceKey param will be null // so the sourceKey will be based on the fake offeringData // and this offering data has a hostname of 'fake.authoring.system' sourceKey: getSourceKey(offeringData.activity_url), userId: fakeUserId() }; } }); }); } export function reportSettingsFireStorePath(LTIData: ILTIPartial) { const {platformId, platformUserId, resourceLinkId} = LTIData; // Note this is similiar to the makeSourceKey function however in this case it is just // stripping off the protocol if there is one. It will also leave any trailing slashes. // It would be best to unify these two approaches. If makeSourceKey is changed then // the LARA make_source_key should be updated as well. const sourceKey = platformId.replace(/https?:\/\//, ""); // NP: 2019-06-28 In the case of fake portal data we will return // `/sources/fake.portal/user_settings/1/offering/class123` which has // special FireStore Rules to allow universal read and write to that document. // Allows us to test limited report settings with fake portal data, sans JWT. // SC: 2019-11-12 this has been updated so the firestore network is disabled so these // fake user_settings should not be saved to or loaded from the actual firestore database return `/sources/${sourceKey}/user_settings/${validFsId(platformUserId)}/resource_link/${validFsId(resourceLinkId)}`; } // The updateReportSettings API middleware calls out to the FireStore API. // `firestore().path().set()` returns a Promise that will resolve immediately. // This due to a feature in the FireStore API called "latency compensation." // See: https://firebase.google.com/docs/firestore/query-data/listen export function updateReportSettings(update: any, state: ILTIPartial) { const path = reportSettingsFireStorePath(state); return firebase.firestore() .doc(path) .set(update, {merge: true}); } export function feedbackSettingsFirestorePath(sourceKey: string, instanceParams?: { platformId?: string; resourceLinkId?: string }) { const path = `/sources/${sourceKey}/feedback_settings`; if (instanceParams) { return path + `/${validFsId(instanceParams.platformId + "-" + instanceParams.resourceLinkId)}`; } return path; } // The updateFeedbackSettings API middleware calls out to the FireStore API. // `firestore().path().set()` returns a Promise that will resolve immediately. // This due to a feature in the FireStore API called "latency compensation." // See: https://firebase.google.com/docs/firestore/query-data/listen // NOTE: this returns promise that might have 3 sub promises, so if this is // used with a callApi successFunction it will have to deal with an array of // parameters. Currently this is not used with a successFunction export function updateFeedbackSettings(data: any, state: IStateReportPartial) { const { settings } = data; const promises: Promise<any>[] = []; // Then, send it to Firestore. settings.platformId = state.platformId; settings.resourceLinkId = state.resourceLinkId; // contextId is used by security rules. settings.contextId = state.contextId; const path = feedbackSettingsFirestorePath(state.sourceKey, {platformId: state.platformId, resourceLinkId: state.resourceLinkId}); const firestorePromise = firebase.firestore() .doc(path) .set(settings, {merge: true}); promises.push(firestorePromise); return Promise.all(promises); } export function reportQuestionFeedbacksFireStorePath(sourceKey: string, answerId?: string) { // NP: 2019-06-28 In the case of fake portal data we will return // `/sources/fake.authoring.system/question_feedbacks/1/` which has // special FireStore Rules to allow universal read and write to that document. // Allows us to test limited report settings with fake portal data, without a JWT. // SC: 2019-11-12 this has been updated so the firestore network is disabled so these // fake question_feedbacks should not be saved to or loaded from the actual firestore database const path = `/sources/${sourceKey}/question_feedbacks`; if (answerId) { return path + `/${answerId}`; } return path; } export function reportActivityFeedbacksFireStorePath(sourceKey: string, activityUserKey?: string) { // NP: 2019-06-28 In the case of fake portal data we will return // `/sources/fake.authoring.system/question_feedbacks/1/` which has // special FireStore Rules to allow universal read and write to that document. // Allows us to test limited report settings with fake portal data, without a JWT. // SC: 2019-11-12 this has been updated so the firestore network is disabled so these // fake activity_feedbacks should not be saved to or loaded from the actual firestore database const path = `/sources/${sourceKey}/activity_feedbacks`; if (activityUserKey) { return path + `/${activityUserKey}`; } return path; } // The updateQuestionFeedbacks API middleware calls out to the FireStore API. // `firestore().path().set()` returns a Promise that will resolve immediately. // This due to a feature in the FireStore API called "latency compensation." // See: https://firebase.google.com/docs/firestore/query-data/listen export function updateQuestionFeedbacks(data: any, reportState: IStateReportPartial) { const { answerId, feedback } = data; const { platformId, platformUserId, resourceLinkId, contextId, answers } = reportState; feedback.platformId = platformId; feedback.resourceLinkId = resourceLinkId; feedback.answerId = answerId; feedback.questionId = answers[answerId].questionId; feedback.platformTeacherId = platformUserId; feedback.platformStudentId = answers[answerId].platformUserId; // contextId is used by security rules. feedback.contextId = contextId; const path = reportQuestionFeedbacksFireStorePath(reportState.sourceKey, answerId); return firebase.firestore() .doc(path) .set(feedback, {merge: true}); } // The updateActivityFeedbacks API middleware calls out to the FireStore API. // `firestore().path().set()` returns a Promise that will resolve immediately. // This due to a feature in the FireStore API called "latency compensation." // See: https://firebase.google.com/docs/firestore/query-data/listen export function updateActivityFeedbacks(data: any, reportState: IStateReportPartial) { const { activityId, platformStudentId, feedback } = data; // Send data to Firestore. const { platformId, platformUserId, resourceLinkId, contextId } = reportState; const activityStudentKey = getActivityStudentFeedbackKey(data); feedback.platformId = platformId; feedback.resourceLinkId = resourceLinkId; feedback.activityId = activityId; feedback.platformTeacherId = platformUserId; feedback.platformStudentId = platformStudentId; feedback.contextId = contextId; const path = reportActivityFeedbacksFireStorePath(reportState.sourceKey, activityStudentKey); return firebase.firestore() .doc(path) .set(feedback, {merge: true}); } // The api-middleware calls this function when we need to load rubric in from a rubricUrl. const rubricUrlCache: any = {}; export function fetchRubric(rubricUrl: string) { return new Promise((resolve, reject) => { if (!rubricUrlCache[rubricUrl]) { fetch(rubricUrl) .then(checkStatus) .then(response => response.json()) .then(newRubric => { rubricUrlCache[rubricUrl] = newRubric; resolve({ url: rubricUrl, rubric: newRubric }); }) .catch(e => { console.error(`unable to load rubric at: ${rubricUrl}`); reject(e); }); } else { // Cache available, resolve promise immediately and return cached value. resolve({rubricUrl, rubric: rubricUrlCache[rubricUrl]}); } }); } // Extend the Error object so we can get stack traces // NOTE: this doesn't work with instanceof checks extending builtin objects has // to be handled specially by transpiliers and when doing that they break the // way instanceof works export class APIError extends Error{ public response: IResponse; constructor(statusText: string, response: IResponse) { super(statusText); this.name = "APIError"; this.response = response; } } function checkStatus(response: Response) { if (response.status >= 200 && response.status < 300) { return response; } else { throw new APIError(response.statusText, response); } }
{ return null; }
conditional_block
api.ts
import * as firebase from "firebase"; import fetch from "isomorphic-fetch"; import * as jwt from "jsonwebtoken"; import ClientOAuth2 from "client-oauth2"; import fakeOfferingData from "./data/offering-data.json"; import fakeClassData from "./data/small-class-data.json"; import { parseUrl, validFsId, urlParam, urlHashParam } from "./util/misc"; import { getActivityStudentFeedbackKey } from "./util/activity-feedback-helper"; import { getFirebaseAppName, signInWithToken } from "./db"; const PORTAL_AUTH_PATH = "/auth/oauth_authorize"; let accessToken: string | null = null; const FAKE_FIRESTORE_JWT = "fake firestore JWT"; export interface ILTIPartial { platformId: string; // portal platformUserId: string; contextId: string; // class hash resourceLinkId: string; // offering ID } export interface IStateAnswer { questionId: string; platformUserId: string; id: string; } export interface IStateReportPartial extends ILTIPartial { answers: {[key: string]: IStateAnswer}; sourceKey: string; } export interface IPortalRawData extends ILTIPartial{ offering: { id: number; activity_url: string; rubric_url: string; }; classInfo: { id: number; name: string; students: IStudentRawData[]; }; userType: "teacher" | "learner"; sourceKey: string; userId: string; } export interface IStudentRawData { first_name: string; last_name: string; user_id: string; } export interface IResponse { url?: string; status: number; statusText: string; } export interface IFirebaseJWT { claims: { user_type: "teacher" | "learner"; platform_id: string; platform_user_id: number; user_id: string; }; } // extract the hostname from the url export const makeSourceKey = (url: string | null) => { return url ? parseUrl(url.toLowerCase()).hostname : ""; }; export const getSourceKey = (url: string): string => { const sourceKeyParam = urlParam("sourceKey"); return sourceKeyParam || makeSourceKey(url); }; // FIXME: If the user isn't logged in, and then they log in with a user that // isn't the student being reported on then just a blank screen is shown export const authorizeInPortal = (portalUrl: string, oauthClientName: string, state: string) => { const portalAuth = new ClientOAuth2({ clientId: oauthClientName, redirectUri: window.location.origin + window.location.pathname, authorizationUri: `${portalUrl}${PORTAL_AUTH_PATH}`, state }); // Redirect window.location.assign(portalAuth.token.getUri()); }; // Returns true if it is redirecting export const initializeAuthorization = () => { const state = urlHashParam("state"); accessToken = urlHashParam("access_token"); if (accessToken && state) { const savedParamString = sessionStorage.getItem(state); window.history.pushState(null, "Portal Report", savedParamString); } else { const authDomain = urlParam("auth-domain"); // Portal has to have AuthClient configured with this clientId. // The AuthClient has to have: // - redirect URLs of each branch being tested // - "client type" needs to be configured as 'public', to allow browser requests const oauthClientName = "portal-report"; if (authDomain) { const key = Math.random().toString(36).substring(2,15); sessionStorage.setItem(key, window.location.search); authorizeInPortal(authDomain, oauthClientName, key); return true; } } return false; }; const getPortalBaseUrl = () => { const portalUrl = urlParam("class") || urlParam("offering"); if (!portalUrl) { return null; } const { hostname, protocol } = parseUrl(portalUrl); return `${protocol}//${hostname}`; }; export const getPortalFirebaseJWTUrl = (classHash: string, resourceLinkId: string | null, targetUserId: string | null, firebaseApp: string | undefined ) => { if(!firebaseApp){ firebaseApp = getFirebaseAppName(); } const baseUrl = getPortalBaseUrl(); if (!baseUrl) { return null; } const resourceLinkParam = resourceLinkId ? `&resource_link_id=${resourceLinkId}` : ""; const targetUserParam = targetUserId ? `&target_user_id=${targetUserId}` : ""; return `${baseUrl}/api/v1/jwt/firebase?firebase_app=${firebaseApp}&class_hash=${classHash}${resourceLinkParam}${targetUserParam}`; }; export function getAuthHeader() { if (urlParam("token")) { return `Bearer ${urlParam("token")}`; } if (accessToken) { return `Bearer ${accessToken}`; } throw new APIError("No token available to set auth header", { status: 0, statusText: "No token available to set auth header" }); } export function fetchOfferingData() { const offeringUrl = urlParam("offering"); if (offeringUrl) { return fetch(offeringUrl, {headers: {Authorization: getAuthHeader()}}) .then(checkStatus) .then((response: Body) => response.json()); } else { return new Promise(resolve => setTimeout(() => resolve(fakeOfferingData), 250)); } } export function fetchClassData() { const classInfoUrl = urlParam("class"); if (classInfoUrl) { return fetch(classInfoUrl, {headers: {Authorization: getAuthHeader()}}) .then(checkStatus) .then(response => response.json()); } else { return new Promise(resolve => setTimeout(() => resolve(fakeClassData), 250)); } } export function fetchFirestoreJWT(classHash: string, resourceLinkId: string | null = null, targetUserId: string | null = null, firebaseApp?: string): Promise<{token: string}> { const firestoreJWTUrl = getPortalFirebaseJWTUrl(classHash, resourceLinkId, targetUserId, firebaseApp ); if (firestoreJWTUrl) { return fetch(firestoreJWTUrl, {headers: {Authorization: getAuthHeader()}}) .then(checkStatus) .then(response => response.json()); } else { return new Promise(resolve => setTimeout(() => resolve({token: FAKE_FIRESTORE_JWT}), 250)); } } export function fetchFirestoreJWTWithDefaultParams(firebaseApp?: string): Promise<{token: string}> { return Promise.all([fetchOfferingData(), fetchClassData()]) .then(([offeringData, classData]) => { const resourceLinkId = offeringData.id.toString(); const studentId = urlParam("studentId"); // only pass resourceLinkId if there is a studentId // This could be a teacher or researcher viewing the report of a student // The studentId is sent in the firestore JWT request as the target_user_id return fetchFirestoreJWT(classData.class_hash, studentId ? resourceLinkId : null, studentId, firebaseApp); }); } export function authFirestore(rawFirestoreJWT: string) { const authResult = signInWithToken(rawFirestoreJWT) as Promise<firebase.auth.UserCredential | void>; return authResult.catch(err => { console.error("Firebase auth failed", err); throw new APIError("Firebase failed", { status: 401, // this will render nice error message that mentions authorization problems statusText: "Firebase authorization failed" }); }); } function fakeUserType(): "teacher" | "learner" { const userType = urlParam("fakeUserType"); if (userType === "teacher" || userType === "learner") { return userType; } return "teacher"; } function fakeUserId() { const userType = urlParam("fakeUserType") || "learner"; return `${userType}@fake.portal`; } export function fetchPortalDataAndAuthFirestore(): Promise<IPortalRawData> { const offeringPromise = fetchOfferingData(); const classPromise = fetchClassData(); return Promise.all([offeringPromise, classPromise]).then(([offeringData, classData]: [any, any]) => { const resourceLinkId = offeringData.id.toString(); const studentId = urlParam("studentId"); // only pass resourceLinkId if there is a studentId // This could be a teacher or researcher viewing the report of a student // The studentId is sent in the firestore JWT request as the target_user_id const firestoreJWTPromise = fetchFirestoreJWT(classData.class_hash, studentId ? resourceLinkId : null, studentId); return firestoreJWTPromise.then((result: any) => { const rawFirestoreJWT = result.token; if (rawFirestoreJWT !== FAKE_FIRESTORE_JWT) { // We're not using fake data. const decodedFirebaseJWT = jwt.decode(rawFirestoreJWT); if (!decodedFirebaseJWT || typeof decodedFirebaseJWT === "string") { throw new APIError("Firebase JWT parsing error", { status: 500, statusText: "Firebase JWT parsing error" }); } const verifiedFirebaseJWT = decodedFirebaseJWT as IFirebaseJWT; return authFirestore(rawFirestoreJWT).then(() => ({ offering: offeringData, resourceLinkId, classInfo: classData, userType: verifiedFirebaseJWT.claims.user_type, platformId: verifiedFirebaseJWT.claims.platform_id, platformUserId: verifiedFirebaseJWT.claims.platform_user_id.toString(), contextId: classData.class_hash, sourceKey: getSourceKey(offeringData.activity_url), userId: verifiedFirebaseJWT.claims.user_id }) ); } else { // We're using fake data, including fake JWT. return { offering: offeringData, resourceLinkId: offeringData.id.toString(), classInfo: classData, userType: fakeUserType(), platformId: "https://fake.portal", platformUserId: urlParam("fakePlatformUserId") || "1", contextId: classData.class_hash, // In most cases when using fake data the sourceKey param will be null // so the sourceKey will be based on the fake offeringData // and this offering data has a hostname of 'fake.authoring.system' sourceKey: getSourceKey(offeringData.activity_url), userId: fakeUserId() };
}); }); } export function reportSettingsFireStorePath(LTIData: ILTIPartial) { const {platformId, platformUserId, resourceLinkId} = LTIData; // Note this is similiar to the makeSourceKey function however in this case it is just // stripping off the protocol if there is one. It will also leave any trailing slashes. // It would be best to unify these two approaches. If makeSourceKey is changed then // the LARA make_source_key should be updated as well. const sourceKey = platformId.replace(/https?:\/\//, ""); // NP: 2019-06-28 In the case of fake portal data we will return // `/sources/fake.portal/user_settings/1/offering/class123` which has // special FireStore Rules to allow universal read and write to that document. // Allows us to test limited report settings with fake portal data, sans JWT. // SC: 2019-11-12 this has been updated so the firestore network is disabled so these // fake user_settings should not be saved to or loaded from the actual firestore database return `/sources/${sourceKey}/user_settings/${validFsId(platformUserId)}/resource_link/${validFsId(resourceLinkId)}`; } // The updateReportSettings API middleware calls out to the FireStore API. // `firestore().path().set()` returns a Promise that will resolve immediately. // This due to a feature in the FireStore API called "latency compensation." // See: https://firebase.google.com/docs/firestore/query-data/listen export function updateReportSettings(update: any, state: ILTIPartial) { const path = reportSettingsFireStorePath(state); return firebase.firestore() .doc(path) .set(update, {merge: true}); } export function feedbackSettingsFirestorePath(sourceKey: string, instanceParams?: { platformId?: string; resourceLinkId?: string }) { const path = `/sources/${sourceKey}/feedback_settings`; if (instanceParams) { return path + `/${validFsId(instanceParams.platformId + "-" + instanceParams.resourceLinkId)}`; } return path; } // The updateFeedbackSettings API middleware calls out to the FireStore API. // `firestore().path().set()` returns a Promise that will resolve immediately. // This due to a feature in the FireStore API called "latency compensation." // See: https://firebase.google.com/docs/firestore/query-data/listen // NOTE: this returns promise that might have 3 sub promises, so if this is // used with a callApi successFunction it will have to deal with an array of // parameters. Currently this is not used with a successFunction export function updateFeedbackSettings(data: any, state: IStateReportPartial) { const { settings } = data; const promises: Promise<any>[] = []; // Then, send it to Firestore. settings.platformId = state.platformId; settings.resourceLinkId = state.resourceLinkId; // contextId is used by security rules. settings.contextId = state.contextId; const path = feedbackSettingsFirestorePath(state.sourceKey, {platformId: state.platformId, resourceLinkId: state.resourceLinkId}); const firestorePromise = firebase.firestore() .doc(path) .set(settings, {merge: true}); promises.push(firestorePromise); return Promise.all(promises); } export function reportQuestionFeedbacksFireStorePath(sourceKey: string, answerId?: string) { // NP: 2019-06-28 In the case of fake portal data we will return // `/sources/fake.authoring.system/question_feedbacks/1/` which has // special FireStore Rules to allow universal read and write to that document. // Allows us to test limited report settings with fake portal data, without a JWT. // SC: 2019-11-12 this has been updated so the firestore network is disabled so these // fake question_feedbacks should not be saved to or loaded from the actual firestore database const path = `/sources/${sourceKey}/question_feedbacks`; if (answerId) { return path + `/${answerId}`; } return path; } export function reportActivityFeedbacksFireStorePath(sourceKey: string, activityUserKey?: string) { // NP: 2019-06-28 In the case of fake portal data we will return // `/sources/fake.authoring.system/question_feedbacks/1/` which has // special FireStore Rules to allow universal read and write to that document. // Allows us to test limited report settings with fake portal data, without a JWT. // SC: 2019-11-12 this has been updated so the firestore network is disabled so these // fake activity_feedbacks should not be saved to or loaded from the actual firestore database const path = `/sources/${sourceKey}/activity_feedbacks`; if (activityUserKey) { return path + `/${activityUserKey}`; } return path; } // The updateQuestionFeedbacks API middleware calls out to the FireStore API. // `firestore().path().set()` returns a Promise that will resolve immediately. // This due to a feature in the FireStore API called "latency compensation." // See: https://firebase.google.com/docs/firestore/query-data/listen export function updateQuestionFeedbacks(data: any, reportState: IStateReportPartial) { const { answerId, feedback } = data; const { platformId, platformUserId, resourceLinkId, contextId, answers } = reportState; feedback.platformId = platformId; feedback.resourceLinkId = resourceLinkId; feedback.answerId = answerId; feedback.questionId = answers[answerId].questionId; feedback.platformTeacherId = platformUserId; feedback.platformStudentId = answers[answerId].platformUserId; // contextId is used by security rules. feedback.contextId = contextId; const path = reportQuestionFeedbacksFireStorePath(reportState.sourceKey, answerId); return firebase.firestore() .doc(path) .set(feedback, {merge: true}); } // The updateActivityFeedbacks API middleware calls out to the FireStore API. // `firestore().path().set()` returns a Promise that will resolve immediately. // This due to a feature in the FireStore API called "latency compensation." // See: https://firebase.google.com/docs/firestore/query-data/listen export function updateActivityFeedbacks(data: any, reportState: IStateReportPartial) { const { activityId, platformStudentId, feedback } = data; // Send data to Firestore. const { platformId, platformUserId, resourceLinkId, contextId } = reportState; const activityStudentKey = getActivityStudentFeedbackKey(data); feedback.platformId = platformId; feedback.resourceLinkId = resourceLinkId; feedback.activityId = activityId; feedback.platformTeacherId = platformUserId; feedback.platformStudentId = platformStudentId; feedback.contextId = contextId; const path = reportActivityFeedbacksFireStorePath(reportState.sourceKey, activityStudentKey); return firebase.firestore() .doc(path) .set(feedback, {merge: true}); } // The api-middleware calls this function when we need to load rubric in from a rubricUrl. const rubricUrlCache: any = {}; export function fetchRubric(rubricUrl: string) { return new Promise((resolve, reject) => { if (!rubricUrlCache[rubricUrl]) { fetch(rubricUrl) .then(checkStatus) .then(response => response.json()) .then(newRubric => { rubricUrlCache[rubricUrl] = newRubric; resolve({ url: rubricUrl, rubric: newRubric }); }) .catch(e => { console.error(`unable to load rubric at: ${rubricUrl}`); reject(e); }); } else { // Cache available, resolve promise immediately and return cached value. resolve({rubricUrl, rubric: rubricUrlCache[rubricUrl]}); } }); } // Extend the Error object so we can get stack traces // NOTE: this doesn't work with instanceof checks extending builtin objects has // to be handled specially by transpiliers and when doing that they break the // way instanceof works export class APIError extends Error{ public response: IResponse; constructor(statusText: string, response: IResponse) { super(statusText); this.name = "APIError"; this.response = response; } } function checkStatus(response: Response) { if (response.status >= 200 && response.status < 300) { return response; } else { throw new APIError(response.statusText, response); } }
}
random_line_split
api.ts
import * as firebase from "firebase"; import fetch from "isomorphic-fetch"; import * as jwt from "jsonwebtoken"; import ClientOAuth2 from "client-oauth2"; import fakeOfferingData from "./data/offering-data.json"; import fakeClassData from "./data/small-class-data.json"; import { parseUrl, validFsId, urlParam, urlHashParam } from "./util/misc"; import { getActivityStudentFeedbackKey } from "./util/activity-feedback-helper"; import { getFirebaseAppName, signInWithToken } from "./db"; const PORTAL_AUTH_PATH = "/auth/oauth_authorize"; let accessToken: string | null = null; const FAKE_FIRESTORE_JWT = "fake firestore JWT"; export interface ILTIPartial { platformId: string; // portal platformUserId: string; contextId: string; // class hash resourceLinkId: string; // offering ID } export interface IStateAnswer { questionId: string; platformUserId: string; id: string; } export interface IStateReportPartial extends ILTIPartial { answers: {[key: string]: IStateAnswer}; sourceKey: string; } export interface IPortalRawData extends ILTIPartial{ offering: { id: number; activity_url: string; rubric_url: string; }; classInfo: { id: number; name: string; students: IStudentRawData[]; }; userType: "teacher" | "learner"; sourceKey: string; userId: string; } export interface IStudentRawData { first_name: string; last_name: string; user_id: string; } export interface IResponse { url?: string; status: number; statusText: string; } export interface IFirebaseJWT { claims: { user_type: "teacher" | "learner"; platform_id: string; platform_user_id: number; user_id: string; }; } // extract the hostname from the url export const makeSourceKey = (url: string | null) => { return url ? parseUrl(url.toLowerCase()).hostname : ""; }; export const getSourceKey = (url: string): string => { const sourceKeyParam = urlParam("sourceKey"); return sourceKeyParam || makeSourceKey(url); }; // FIXME: If the user isn't logged in, and then they log in with a user that // isn't the student being reported on then just a blank screen is shown export const authorizeInPortal = (portalUrl: string, oauthClientName: string, state: string) => { const portalAuth = new ClientOAuth2({ clientId: oauthClientName, redirectUri: window.location.origin + window.location.pathname, authorizationUri: `${portalUrl}${PORTAL_AUTH_PATH}`, state }); // Redirect window.location.assign(portalAuth.token.getUri()); }; // Returns true if it is redirecting export const initializeAuthorization = () => { const state = urlHashParam("state"); accessToken = urlHashParam("access_token"); if (accessToken && state) { const savedParamString = sessionStorage.getItem(state); window.history.pushState(null, "Portal Report", savedParamString); } else { const authDomain = urlParam("auth-domain"); // Portal has to have AuthClient configured with this clientId. // The AuthClient has to have: // - redirect URLs of each branch being tested // - "client type" needs to be configured as 'public', to allow browser requests const oauthClientName = "portal-report"; if (authDomain) { const key = Math.random().toString(36).substring(2,15); sessionStorage.setItem(key, window.location.search); authorizeInPortal(authDomain, oauthClientName, key); return true; } } return false; }; const getPortalBaseUrl = () => { const portalUrl = urlParam("class") || urlParam("offering"); if (!portalUrl) { return null; } const { hostname, protocol } = parseUrl(portalUrl); return `${protocol}//${hostname}`; }; export const getPortalFirebaseJWTUrl = (classHash: string, resourceLinkId: string | null, targetUserId: string | null, firebaseApp: string | undefined ) => { if(!firebaseApp){ firebaseApp = getFirebaseAppName(); } const baseUrl = getPortalBaseUrl(); if (!baseUrl) { return null; } const resourceLinkParam = resourceLinkId ? `&resource_link_id=${resourceLinkId}` : ""; const targetUserParam = targetUserId ? `&target_user_id=${targetUserId}` : ""; return `${baseUrl}/api/v1/jwt/firebase?firebase_app=${firebaseApp}&class_hash=${classHash}${resourceLinkParam}${targetUserParam}`; }; export function getAuthHeader()
export function fetchOfferingData() { const offeringUrl = urlParam("offering"); if (offeringUrl) { return fetch(offeringUrl, {headers: {Authorization: getAuthHeader()}}) .then(checkStatus) .then((response: Body) => response.json()); } else { return new Promise(resolve => setTimeout(() => resolve(fakeOfferingData), 250)); } } export function fetchClassData() { const classInfoUrl = urlParam("class"); if (classInfoUrl) { return fetch(classInfoUrl, {headers: {Authorization: getAuthHeader()}}) .then(checkStatus) .then(response => response.json()); } else { return new Promise(resolve => setTimeout(() => resolve(fakeClassData), 250)); } } export function fetchFirestoreJWT(classHash: string, resourceLinkId: string | null = null, targetUserId: string | null = null, firebaseApp?: string): Promise<{token: string}> { const firestoreJWTUrl = getPortalFirebaseJWTUrl(classHash, resourceLinkId, targetUserId, firebaseApp ); if (firestoreJWTUrl) { return fetch(firestoreJWTUrl, {headers: {Authorization: getAuthHeader()}}) .then(checkStatus) .then(response => response.json()); } else { return new Promise(resolve => setTimeout(() => resolve({token: FAKE_FIRESTORE_JWT}), 250)); } } export function fetchFirestoreJWTWithDefaultParams(firebaseApp?: string): Promise<{token: string}> { return Promise.all([fetchOfferingData(), fetchClassData()]) .then(([offeringData, classData]) => { const resourceLinkId = offeringData.id.toString(); const studentId = urlParam("studentId"); // only pass resourceLinkId if there is a studentId // This could be a teacher or researcher viewing the report of a student // The studentId is sent in the firestore JWT request as the target_user_id return fetchFirestoreJWT(classData.class_hash, studentId ? resourceLinkId : null, studentId, firebaseApp); }); } export function authFirestore(rawFirestoreJWT: string) { const authResult = signInWithToken(rawFirestoreJWT) as Promise<firebase.auth.UserCredential | void>; return authResult.catch(err => { console.error("Firebase auth failed", err); throw new APIError("Firebase failed", { status: 401, // this will render nice error message that mentions authorization problems statusText: "Firebase authorization failed" }); }); } function fakeUserType(): "teacher" | "learner" { const userType = urlParam("fakeUserType"); if (userType === "teacher" || userType === "learner") { return userType; } return "teacher"; } function fakeUserId() { const userType = urlParam("fakeUserType") || "learner"; return `${userType}@fake.portal`; } export function fetchPortalDataAndAuthFirestore(): Promise<IPortalRawData> { const offeringPromise = fetchOfferingData(); const classPromise = fetchClassData(); return Promise.all([offeringPromise, classPromise]).then(([offeringData, classData]: [any, any]) => { const resourceLinkId = offeringData.id.toString(); const studentId = urlParam("studentId"); // only pass resourceLinkId if there is a studentId // This could be a teacher or researcher viewing the report of a student // The studentId is sent in the firestore JWT request as the target_user_id const firestoreJWTPromise = fetchFirestoreJWT(classData.class_hash, studentId ? resourceLinkId : null, studentId); return firestoreJWTPromise.then((result: any) => { const rawFirestoreJWT = result.token; if (rawFirestoreJWT !== FAKE_FIRESTORE_JWT) { // We're not using fake data. const decodedFirebaseJWT = jwt.decode(rawFirestoreJWT); if (!decodedFirebaseJWT || typeof decodedFirebaseJWT === "string") { throw new APIError("Firebase JWT parsing error", { status: 500, statusText: "Firebase JWT parsing error" }); } const verifiedFirebaseJWT = decodedFirebaseJWT as IFirebaseJWT; return authFirestore(rawFirestoreJWT).then(() => ({ offering: offeringData, resourceLinkId, classInfo: classData, userType: verifiedFirebaseJWT.claims.user_type, platformId: verifiedFirebaseJWT.claims.platform_id, platformUserId: verifiedFirebaseJWT.claims.platform_user_id.toString(), contextId: classData.class_hash, sourceKey: getSourceKey(offeringData.activity_url), userId: verifiedFirebaseJWT.claims.user_id }) ); } else { // We're using fake data, including fake JWT. return { offering: offeringData, resourceLinkId: offeringData.id.toString(), classInfo: classData, userType: fakeUserType(), platformId: "https://fake.portal", platformUserId: urlParam("fakePlatformUserId") || "1", contextId: classData.class_hash, // In most cases when using fake data the sourceKey param will be null // so the sourceKey will be based on the fake offeringData // and this offering data has a hostname of 'fake.authoring.system' sourceKey: getSourceKey(offeringData.activity_url), userId: fakeUserId() }; } }); }); } export function reportSettingsFireStorePath(LTIData: ILTIPartial) { const {platformId, platformUserId, resourceLinkId} = LTIData; // Note this is similiar to the makeSourceKey function however in this case it is just // stripping off the protocol if there is one. It will also leave any trailing slashes. // It would be best to unify these two approaches. If makeSourceKey is changed then // the LARA make_source_key should be updated as well. const sourceKey = platformId.replace(/https?:\/\//, ""); // NP: 2019-06-28 In the case of fake portal data we will return // `/sources/fake.portal/user_settings/1/offering/class123` which has // special FireStore Rules to allow universal read and write to that document. // Allows us to test limited report settings with fake portal data, sans JWT. // SC: 2019-11-12 this has been updated so the firestore network is disabled so these // fake user_settings should not be saved to or loaded from the actual firestore database return `/sources/${sourceKey}/user_settings/${validFsId(platformUserId)}/resource_link/${validFsId(resourceLinkId)}`; } // The updateReportSettings API middleware calls out to the FireStore API. // `firestore().path().set()` returns a Promise that will resolve immediately. // This due to a feature in the FireStore API called "latency compensation." // See: https://firebase.google.com/docs/firestore/query-data/listen export function updateReportSettings(update: any, state: ILTIPartial) { const path = reportSettingsFireStorePath(state); return firebase.firestore() .doc(path) .set(update, {merge: true}); } export function feedbackSettingsFirestorePath(sourceKey: string, instanceParams?: { platformId?: string; resourceLinkId?: string }) { const path = `/sources/${sourceKey}/feedback_settings`; if (instanceParams) { return path + `/${validFsId(instanceParams.platformId + "-" + instanceParams.resourceLinkId)}`; } return path; } // The updateFeedbackSettings API middleware calls out to the FireStore API. // `firestore().path().set()` returns a Promise that will resolve immediately. // This due to a feature in the FireStore API called "latency compensation." // See: https://firebase.google.com/docs/firestore/query-data/listen // NOTE: this returns promise that might have 3 sub promises, so if this is // used with a callApi successFunction it will have to deal with an array of // parameters. Currently this is not used with a successFunction export function updateFeedbackSettings(data: any, state: IStateReportPartial) { const { settings } = data; const promises: Promise<any>[] = []; // Then, send it to Firestore. settings.platformId = state.platformId; settings.resourceLinkId = state.resourceLinkId; // contextId is used by security rules. settings.contextId = state.contextId; const path = feedbackSettingsFirestorePath(state.sourceKey, {platformId: state.platformId, resourceLinkId: state.resourceLinkId}); const firestorePromise = firebase.firestore() .doc(path) .set(settings, {merge: true}); promises.push(firestorePromise); return Promise.all(promises); } export function reportQuestionFeedbacksFireStorePath(sourceKey: string, answerId?: string) { // NP: 2019-06-28 In the case of fake portal data we will return // `/sources/fake.authoring.system/question_feedbacks/1/` which has // special FireStore Rules to allow universal read and write to that document. // Allows us to test limited report settings with fake portal data, without a JWT. // SC: 2019-11-12 this has been updated so the firestore network is disabled so these // fake question_feedbacks should not be saved to or loaded from the actual firestore database const path = `/sources/${sourceKey}/question_feedbacks`; if (answerId) { return path + `/${answerId}`; } return path; } export function reportActivityFeedbacksFireStorePath(sourceKey: string, activityUserKey?: string) { // NP: 2019-06-28 In the case of fake portal data we will return // `/sources/fake.authoring.system/question_feedbacks/1/` which has // special FireStore Rules to allow universal read and write to that document. // Allows us to test limited report settings with fake portal data, without a JWT. // SC: 2019-11-12 this has been updated so the firestore network is disabled so these // fake activity_feedbacks should not be saved to or loaded from the actual firestore database const path = `/sources/${sourceKey}/activity_feedbacks`; if (activityUserKey) { return path + `/${activityUserKey}`; } return path; } // The updateQuestionFeedbacks API middleware calls out to the FireStore API. // `firestore().path().set()` returns a Promise that will resolve immediately. // This due to a feature in the FireStore API called "latency compensation." // See: https://firebase.google.com/docs/firestore/query-data/listen export function updateQuestionFeedbacks(data: any, reportState: IStateReportPartial) { const { answerId, feedback } = data; const { platformId, platformUserId, resourceLinkId, contextId, answers } = reportState; feedback.platformId = platformId; feedback.resourceLinkId = resourceLinkId; feedback.answerId = answerId; feedback.questionId = answers[answerId].questionId; feedback.platformTeacherId = platformUserId; feedback.platformStudentId = answers[answerId].platformUserId; // contextId is used by security rules. feedback.contextId = contextId; const path = reportQuestionFeedbacksFireStorePath(reportState.sourceKey, answerId); return firebase.firestore() .doc(path) .set(feedback, {merge: true}); } // The updateActivityFeedbacks API middleware calls out to the FireStore API. // `firestore().path().set()` returns a Promise that will resolve immediately. // This due to a feature in the FireStore API called "latency compensation." // See: https://firebase.google.com/docs/firestore/query-data/listen export function updateActivityFeedbacks(data: any, reportState: IStateReportPartial) { const { activityId, platformStudentId, feedback } = data; // Send data to Firestore. const { platformId, platformUserId, resourceLinkId, contextId } = reportState; const activityStudentKey = getActivityStudentFeedbackKey(data); feedback.platformId = platformId; feedback.resourceLinkId = resourceLinkId; feedback.activityId = activityId; feedback.platformTeacherId = platformUserId; feedback.platformStudentId = platformStudentId; feedback.contextId = contextId; const path = reportActivityFeedbacksFireStorePath(reportState.sourceKey, activityStudentKey); return firebase.firestore() .doc(path) .set(feedback, {merge: true}); } // The api-middleware calls this function when we need to load rubric in from a rubricUrl. const rubricUrlCache: any = {}; export function fetchRubric(rubricUrl: string) { return new Promise((resolve, reject) => { if (!rubricUrlCache[rubricUrl]) { fetch(rubricUrl) .then(checkStatus) .then(response => response.json()) .then(newRubric => { rubricUrlCache[rubricUrl] = newRubric; resolve({ url: rubricUrl, rubric: newRubric }); }) .catch(e => { console.error(`unable to load rubric at: ${rubricUrl}`); reject(e); }); } else { // Cache available, resolve promise immediately and return cached value. resolve({rubricUrl, rubric: rubricUrlCache[rubricUrl]}); } }); } // Extend the Error object so we can get stack traces // NOTE: this doesn't work with instanceof checks extending builtin objects has // to be handled specially by transpiliers and when doing that they break the // way instanceof works export class APIError extends Error{ public response: IResponse; constructor(statusText: string, response: IResponse) { super(statusText); this.name = "APIError"; this.response = response; } } function checkStatus(response: Response) { if (response.status >= 200 && response.status < 300) { return response; } else { throw new APIError(response.statusText, response); } }
{ if (urlParam("token")) { return `Bearer ${urlParam("token")}`; } if (accessToken) { return `Bearer ${accessToken}`; } throw new APIError("No token available to set auth header", { status: 0, statusText: "No token available to set auth header" }); }
identifier_body
api.ts
import * as firebase from "firebase"; import fetch from "isomorphic-fetch"; import * as jwt from "jsonwebtoken"; import ClientOAuth2 from "client-oauth2"; import fakeOfferingData from "./data/offering-data.json"; import fakeClassData from "./data/small-class-data.json"; import { parseUrl, validFsId, urlParam, urlHashParam } from "./util/misc"; import { getActivityStudentFeedbackKey } from "./util/activity-feedback-helper"; import { getFirebaseAppName, signInWithToken } from "./db"; const PORTAL_AUTH_PATH = "/auth/oauth_authorize"; let accessToken: string | null = null; const FAKE_FIRESTORE_JWT = "fake firestore JWT"; export interface ILTIPartial { platformId: string; // portal platformUserId: string; contextId: string; // class hash resourceLinkId: string; // offering ID } export interface IStateAnswer { questionId: string; platformUserId: string; id: string; } export interface IStateReportPartial extends ILTIPartial { answers: {[key: string]: IStateAnswer}; sourceKey: string; } export interface IPortalRawData extends ILTIPartial{ offering: { id: number; activity_url: string; rubric_url: string; }; classInfo: { id: number; name: string; students: IStudentRawData[]; }; userType: "teacher" | "learner"; sourceKey: string; userId: string; } export interface IStudentRawData { first_name: string; last_name: string; user_id: string; } export interface IResponse { url?: string; status: number; statusText: string; } export interface IFirebaseJWT { claims: { user_type: "teacher" | "learner"; platform_id: string; platform_user_id: number; user_id: string; }; } // extract the hostname from the url export const makeSourceKey = (url: string | null) => { return url ? parseUrl(url.toLowerCase()).hostname : ""; }; export const getSourceKey = (url: string): string => { const sourceKeyParam = urlParam("sourceKey"); return sourceKeyParam || makeSourceKey(url); }; // FIXME: If the user isn't logged in, and then they log in with a user that // isn't the student being reported on then just a blank screen is shown export const authorizeInPortal = (portalUrl: string, oauthClientName: string, state: string) => { const portalAuth = new ClientOAuth2({ clientId: oauthClientName, redirectUri: window.location.origin + window.location.pathname, authorizationUri: `${portalUrl}${PORTAL_AUTH_PATH}`, state }); // Redirect window.location.assign(portalAuth.token.getUri()); }; // Returns true if it is redirecting export const initializeAuthorization = () => { const state = urlHashParam("state"); accessToken = urlHashParam("access_token"); if (accessToken && state) { const savedParamString = sessionStorage.getItem(state); window.history.pushState(null, "Portal Report", savedParamString); } else { const authDomain = urlParam("auth-domain"); // Portal has to have AuthClient configured with this clientId. // The AuthClient has to have: // - redirect URLs of each branch being tested // - "client type" needs to be configured as 'public', to allow browser requests const oauthClientName = "portal-report"; if (authDomain) { const key = Math.random().toString(36).substring(2,15); sessionStorage.setItem(key, window.location.search); authorizeInPortal(authDomain, oauthClientName, key); return true; } } return false; }; const getPortalBaseUrl = () => { const portalUrl = urlParam("class") || urlParam("offering"); if (!portalUrl) { return null; } const { hostname, protocol } = parseUrl(portalUrl); return `${protocol}//${hostname}`; }; export const getPortalFirebaseJWTUrl = (classHash: string, resourceLinkId: string | null, targetUserId: string | null, firebaseApp: string | undefined ) => { if(!firebaseApp){ firebaseApp = getFirebaseAppName(); } const baseUrl = getPortalBaseUrl(); if (!baseUrl) { return null; } const resourceLinkParam = resourceLinkId ? `&resource_link_id=${resourceLinkId}` : ""; const targetUserParam = targetUserId ? `&target_user_id=${targetUserId}` : ""; return `${baseUrl}/api/v1/jwt/firebase?firebase_app=${firebaseApp}&class_hash=${classHash}${resourceLinkParam}${targetUserParam}`; }; export function getAuthHeader() { if (urlParam("token")) { return `Bearer ${urlParam("token")}`; } if (accessToken) { return `Bearer ${accessToken}`; } throw new APIError("No token available to set auth header", { status: 0, statusText: "No token available to set auth header" }); } export function fetchOfferingData() { const offeringUrl = urlParam("offering"); if (offeringUrl) { return fetch(offeringUrl, {headers: {Authorization: getAuthHeader()}}) .then(checkStatus) .then((response: Body) => response.json()); } else { return new Promise(resolve => setTimeout(() => resolve(fakeOfferingData), 250)); } } export function fetchClassData() { const classInfoUrl = urlParam("class"); if (classInfoUrl) { return fetch(classInfoUrl, {headers: {Authorization: getAuthHeader()}}) .then(checkStatus) .then(response => response.json()); } else { return new Promise(resolve => setTimeout(() => resolve(fakeClassData), 250)); } } export function fetchFirestoreJWT(classHash: string, resourceLinkId: string | null = null, targetUserId: string | null = null, firebaseApp?: string): Promise<{token: string}> { const firestoreJWTUrl = getPortalFirebaseJWTUrl(classHash, resourceLinkId, targetUserId, firebaseApp ); if (firestoreJWTUrl) { return fetch(firestoreJWTUrl, {headers: {Authorization: getAuthHeader()}}) .then(checkStatus) .then(response => response.json()); } else { return new Promise(resolve => setTimeout(() => resolve({token: FAKE_FIRESTORE_JWT}), 250)); } } export function fetchFirestoreJWTWithDefaultParams(firebaseApp?: string): Promise<{token: string}> { return Promise.all([fetchOfferingData(), fetchClassData()]) .then(([offeringData, classData]) => { const resourceLinkId = offeringData.id.toString(); const studentId = urlParam("studentId"); // only pass resourceLinkId if there is a studentId // This could be a teacher or researcher viewing the report of a student // The studentId is sent in the firestore JWT request as the target_user_id return fetchFirestoreJWT(classData.class_hash, studentId ? resourceLinkId : null, studentId, firebaseApp); }); } export function authFirestore(rawFirestoreJWT: string) { const authResult = signInWithToken(rawFirestoreJWT) as Promise<firebase.auth.UserCredential | void>; return authResult.catch(err => { console.error("Firebase auth failed", err); throw new APIError("Firebase failed", { status: 401, // this will render nice error message that mentions authorization problems statusText: "Firebase authorization failed" }); }); } function fakeUserType(): "teacher" | "learner" { const userType = urlParam("fakeUserType"); if (userType === "teacher" || userType === "learner") { return userType; } return "teacher"; } function fakeUserId() { const userType = urlParam("fakeUserType") || "learner"; return `${userType}@fake.portal`; } export function fetchPortalDataAndAuthFirestore(): Promise<IPortalRawData> { const offeringPromise = fetchOfferingData(); const classPromise = fetchClassData(); return Promise.all([offeringPromise, classPromise]).then(([offeringData, classData]: [any, any]) => { const resourceLinkId = offeringData.id.toString(); const studentId = urlParam("studentId"); // only pass resourceLinkId if there is a studentId // This could be a teacher or researcher viewing the report of a student // The studentId is sent in the firestore JWT request as the target_user_id const firestoreJWTPromise = fetchFirestoreJWT(classData.class_hash, studentId ? resourceLinkId : null, studentId); return firestoreJWTPromise.then((result: any) => { const rawFirestoreJWT = result.token; if (rawFirestoreJWT !== FAKE_FIRESTORE_JWT) { // We're not using fake data. const decodedFirebaseJWT = jwt.decode(rawFirestoreJWT); if (!decodedFirebaseJWT || typeof decodedFirebaseJWT === "string") { throw new APIError("Firebase JWT parsing error", { status: 500, statusText: "Firebase JWT parsing error" }); } const verifiedFirebaseJWT = decodedFirebaseJWT as IFirebaseJWT; return authFirestore(rawFirestoreJWT).then(() => ({ offering: offeringData, resourceLinkId, classInfo: classData, userType: verifiedFirebaseJWT.claims.user_type, platformId: verifiedFirebaseJWT.claims.platform_id, platformUserId: verifiedFirebaseJWT.claims.platform_user_id.toString(), contextId: classData.class_hash, sourceKey: getSourceKey(offeringData.activity_url), userId: verifiedFirebaseJWT.claims.user_id }) ); } else { // We're using fake data, including fake JWT. return { offering: offeringData, resourceLinkId: offeringData.id.toString(), classInfo: classData, userType: fakeUserType(), platformId: "https://fake.portal", platformUserId: urlParam("fakePlatformUserId") || "1", contextId: classData.class_hash, // In most cases when using fake data the sourceKey param will be null // so the sourceKey will be based on the fake offeringData // and this offering data has a hostname of 'fake.authoring.system' sourceKey: getSourceKey(offeringData.activity_url), userId: fakeUserId() }; } }); }); } export function reportSettingsFireStorePath(LTIData: ILTIPartial) { const {platformId, platformUserId, resourceLinkId} = LTIData; // Note this is similiar to the makeSourceKey function however in this case it is just // stripping off the protocol if there is one. It will also leave any trailing slashes. // It would be best to unify these two approaches. If makeSourceKey is changed then // the LARA make_source_key should be updated as well. const sourceKey = platformId.replace(/https?:\/\//, ""); // NP: 2019-06-28 In the case of fake portal data we will return // `/sources/fake.portal/user_settings/1/offering/class123` which has // special FireStore Rules to allow universal read and write to that document. // Allows us to test limited report settings with fake portal data, sans JWT. // SC: 2019-11-12 this has been updated so the firestore network is disabled so these // fake user_settings should not be saved to or loaded from the actual firestore database return `/sources/${sourceKey}/user_settings/${validFsId(platformUserId)}/resource_link/${validFsId(resourceLinkId)}`; } // The updateReportSettings API middleware calls out to the FireStore API. // `firestore().path().set()` returns a Promise that will resolve immediately. // This due to a feature in the FireStore API called "latency compensation." // See: https://firebase.google.com/docs/firestore/query-data/listen export function updateReportSettings(update: any, state: ILTIPartial) { const path = reportSettingsFireStorePath(state); return firebase.firestore() .doc(path) .set(update, {merge: true}); } export function
(sourceKey: string, instanceParams?: { platformId?: string; resourceLinkId?: string }) { const path = `/sources/${sourceKey}/feedback_settings`; if (instanceParams) { return path + `/${validFsId(instanceParams.platformId + "-" + instanceParams.resourceLinkId)}`; } return path; } // The updateFeedbackSettings API middleware calls out to the FireStore API. // `firestore().path().set()` returns a Promise that will resolve immediately. // This due to a feature in the FireStore API called "latency compensation." // See: https://firebase.google.com/docs/firestore/query-data/listen // NOTE: this returns promise that might have 3 sub promises, so if this is // used with a callApi successFunction it will have to deal with an array of // parameters. Currently this is not used with a successFunction export function updateFeedbackSettings(data: any, state: IStateReportPartial) { const { settings } = data; const promises: Promise<any>[] = []; // Then, send it to Firestore. settings.platformId = state.platformId; settings.resourceLinkId = state.resourceLinkId; // contextId is used by security rules. settings.contextId = state.contextId; const path = feedbackSettingsFirestorePath(state.sourceKey, {platformId: state.platformId, resourceLinkId: state.resourceLinkId}); const firestorePromise = firebase.firestore() .doc(path) .set(settings, {merge: true}); promises.push(firestorePromise); return Promise.all(promises); } export function reportQuestionFeedbacksFireStorePath(sourceKey: string, answerId?: string) { // NP: 2019-06-28 In the case of fake portal data we will return // `/sources/fake.authoring.system/question_feedbacks/1/` which has // special FireStore Rules to allow universal read and write to that document. // Allows us to test limited report settings with fake portal data, without a JWT. // SC: 2019-11-12 this has been updated so the firestore network is disabled so these // fake question_feedbacks should not be saved to or loaded from the actual firestore database const path = `/sources/${sourceKey}/question_feedbacks`; if (answerId) { return path + `/${answerId}`; } return path; } export function reportActivityFeedbacksFireStorePath(sourceKey: string, activityUserKey?: string) { // NP: 2019-06-28 In the case of fake portal data we will return // `/sources/fake.authoring.system/question_feedbacks/1/` which has // special FireStore Rules to allow universal read and write to that document. // Allows us to test limited report settings with fake portal data, without a JWT. // SC: 2019-11-12 this has been updated so the firestore network is disabled so these // fake activity_feedbacks should not be saved to or loaded from the actual firestore database const path = `/sources/${sourceKey}/activity_feedbacks`; if (activityUserKey) { return path + `/${activityUserKey}`; } return path; } // The updateQuestionFeedbacks API middleware calls out to the FireStore API. // `firestore().path().set()` returns a Promise that will resolve immediately. // This due to a feature in the FireStore API called "latency compensation." // See: https://firebase.google.com/docs/firestore/query-data/listen export function updateQuestionFeedbacks(data: any, reportState: IStateReportPartial) { const { answerId, feedback } = data; const { platformId, platformUserId, resourceLinkId, contextId, answers } = reportState; feedback.platformId = platformId; feedback.resourceLinkId = resourceLinkId; feedback.answerId = answerId; feedback.questionId = answers[answerId].questionId; feedback.platformTeacherId = platformUserId; feedback.platformStudentId = answers[answerId].platformUserId; // contextId is used by security rules. feedback.contextId = contextId; const path = reportQuestionFeedbacksFireStorePath(reportState.sourceKey, answerId); return firebase.firestore() .doc(path) .set(feedback, {merge: true}); } // The updateActivityFeedbacks API middleware calls out to the FireStore API. // `firestore().path().set()` returns a Promise that will resolve immediately. // This due to a feature in the FireStore API called "latency compensation." // See: https://firebase.google.com/docs/firestore/query-data/listen export function updateActivityFeedbacks(data: any, reportState: IStateReportPartial) { const { activityId, platformStudentId, feedback } = data; // Send data to Firestore. const { platformId, platformUserId, resourceLinkId, contextId } = reportState; const activityStudentKey = getActivityStudentFeedbackKey(data); feedback.platformId = platformId; feedback.resourceLinkId = resourceLinkId; feedback.activityId = activityId; feedback.platformTeacherId = platformUserId; feedback.platformStudentId = platformStudentId; feedback.contextId = contextId; const path = reportActivityFeedbacksFireStorePath(reportState.sourceKey, activityStudentKey); return firebase.firestore() .doc(path) .set(feedback, {merge: true}); } // The api-middleware calls this function when we need to load rubric in from a rubricUrl. const rubricUrlCache: any = {}; export function fetchRubric(rubricUrl: string) { return new Promise((resolve, reject) => { if (!rubricUrlCache[rubricUrl]) { fetch(rubricUrl) .then(checkStatus) .then(response => response.json()) .then(newRubric => { rubricUrlCache[rubricUrl] = newRubric; resolve({ url: rubricUrl, rubric: newRubric }); }) .catch(e => { console.error(`unable to load rubric at: ${rubricUrl}`); reject(e); }); } else { // Cache available, resolve promise immediately and return cached value. resolve({rubricUrl, rubric: rubricUrlCache[rubricUrl]}); } }); } // Extend the Error object so we can get stack traces // NOTE: this doesn't work with instanceof checks extending builtin objects has // to be handled specially by transpiliers and when doing that they break the // way instanceof works export class APIError extends Error{ public response: IResponse; constructor(statusText: string, response: IResponse) { super(statusText); this.name = "APIError"; this.response = response; } } function checkStatus(response: Response) { if (response.status >= 200 && response.status < 300) { return response; } else { throw new APIError(response.statusText, response); } }
feedbackSettingsFirestorePath
identifier_name
codegen_common.py
#!/usr/bin/python ########################################################################## # # MTraceCheck # Copyright 2017 The Regents of the University of Michigan # Doowon Lee and Valeria Bertacco # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ########################################################################## # # This file should be called from codegen.py # #################################################################### # Data section #################################################################### def generate_data_section(dataName, memLocs, strideType): assert(memLocs <= 0x10000) #dataArray = [] #for i in range(memLocs): # data = [i & 0xFF, (i >> 8) & 0xFF, 0xFF, 0xFF] # dataArray += data ## Data contents will be initialized in test manager, so just create a placeholder if (strideType == 0): dataArray = [0xFF for i in range(memLocs * 4 * 1)] elif (strideType == 1): dataArray = [0xFF for i in range(memLocs * 4 * 4)] elif (strideType == 2): dataArray = [0xFF for i in range(memLocs * 4 * 16)] else: assert(False) dataFP = open(dataName, "w") dataFP.write(bytearray(dataArray)) dataFP.close() #################################################################### # BSS section (section to be written by test threads) #################################################################### def generate_bss_section(bssName, bssSize): #bssArray = [] #for i in range(bssSize): # bssArray += [0x00] #bssFP = open(bssName, "w") #bssFP.write(bytearray(bssArray)) #bssFP.close() # Faster code bssFP = open(bssName, "wb") bssFP.seek(bssSize-1) bssFP.write("\0") bssFP.close() #################################################################### # Test manager CPP file #################################################################### def generate_test_manager(cppName, headerName, threadList, bssBase, bssSizePerThread, signatureSize, regBitWidth, numExecutions, strideType): # See an example of cpp file at exp/160815_test_manager/test_manager.cpp # (This example is possibly outdated) wordTypeString = "uint%d_t" % regBitWidth cppString = "" cppString += "#include <stdio.h>\n" cppString += "#include <stdlib.h>\n" cppString += "#include <stdint.h>\n" cppString += "#include <pthread.h>\n" cppString += "#include <map>\n" cppString += "#include <vector>\n" cppString += "#include \"%s\"\n" % headerName for thread in threadList: cppString += "extern \"C\" void* thread%d_routine(void*);\n" % thread cppString += "volatile int thread_spawn_lock = 0;\n" cppString += "#ifdef EXEC_SYNC\n" cppString += "volatile int thread_exec_barrier0 = 0;\n" cppString += "volatile int thread_exec_barrier1 = 0;\n" cppString += "volatile int thread_exec_barrier_ptr = 0;\n" cppString += "#endif\n" cppString += "int main()\n" cppString += "{\n" cppString += " int pthread_return;\n" cppString += " int numThreads = %d;\n" % len(threadList) cppString += " // Test BSS section initialization\n" cppString += " %s *bss_address = (%s *) TEST_BSS_SECTION;\n" % (wordTypeString, wordTypeString) cppString += " for (int i = 0; i < numThreads * TEST_BSS_SIZE_PER_THREAD; i += sizeof(%s)) {\n" % (wordTypeString) cppString += " *(bss_address++) = 0;\n" cppString += " }\n" cppString += " // Test data section initialization\n" cppString += " uint32_t *data_address= (uint32_t *) TEST_DATA_SECTION;\n" cppString += " for (int i = 0; i < NUM_SHARED_DATA; i++) {\n" cppString += " *data_address = (uint32_t) (0xFFFF0000 | i);\n" if (strideType == 0): cppString += " data_address++; // strideType = 0\n" elif (strideType == 1): cppString += " data_address+=4; // strideType = 1\n" elif (strideType == 2): cppString += " data_address+=16; // strideType = 2\n" else: assert(False) cppString += " }\n" cppString += " pthread_t* threads = (pthread_t *) malloc(sizeof(pthread_t) * numThreads);\n" for threadIndex in range(len(threadList)): cppString += " pthread_return = pthread_create(&threads[%d], NULL, thread%d_routine, NULL);\n" % (threadIndex, threadList[threadIndex]) cppString += " for (int t = 0; t < numThreads; t++)\n" cppString += " pthread_return = pthread_join(threads[t], NULL);\n" cppString += " std::map<std::vector<%s>, int> signatureMap;\n" % (wordTypeString) cppString += " std::vector<%s> resultVector;\n" % (wordTypeString) cppString += " %s *signature = (%s *) TEST_BSS_SECTION;\n" % (wordTypeString, wordTypeString) cppString += " for (int i = 0; i < EXECUTION_COUNT; i++) {\n" cppString += " resultVector.clear();\n" #cppString += "#ifndef NO_PRINT\n" cppString += "#if 0\n" cppString += " printf(\"%8d:\", i);\n" cppString += "#endif\n" cppString += " for (int t = 0; t < numThreads; t++) {\n" cppString += " for (int w = 0; w < SIGNATURE_SIZE_IN_WORD; w++) {\n" # NOTE: SIGNATURE WORD REORDERING #cppString += " for (int w = SIGNATURE_SIZE_IN_WORD - 1; w >= 0; w--) {\n" #cppString += " for (int t = 0; t < numThreads; t++) {\n" cppString += " %s address = (%s) signature + t * TEST_BSS_SIZE_PER_THREAD + w * sizeof(%s);\n" % (wordTypeString, wordTypeString, wordTypeString) cppString += " %s result = (%s)*(%s*)address;\n" % (wordTypeString, wordTypeString, wordTypeString) cppString += " resultVector.push_back(result);\n" #cppString += "#ifndef NO_PRINT\n" cppString += "#if 0\n" cppString += " printf(\" 0x%%0%dlx\", result);\n" % (regBitWidth / 8 * 2) #cppString += " printf(\" 0x%%lx 0x%%0%dlx\", address, result);\n" % signatureSize cppString += "#endif\n" cppString += " }\n" cppString += " }\n" cppString += " if (signatureMap.find(resultVector) == signatureMap.end())\n" cppString += " signatureMap[resultVector] = 1;\n" cppString += " else\n" cppString += " signatureMap[resultVector]++;\n" #cppString += "#ifndef NO_PRINT\n" cppString += "#if 0\n" cppString += " printf(\"\\n\");\n" cppString += "#endif\n" cppString += " signature += SIGNATURE_SIZE_IN_WORD;\n" cppString += " }\n" cppString += "#ifndef NO_PRINT\n" cppString += " for (std::map<std::vector<%s>, int>::iterator it = signatureMap.begin(); it != signatureMap.end(); it++) {\n" % (wordTypeString) cppString += " for (int i = 0; i < (it->first).size(); i++)\n" cppString += " printf(\" 0x%%0%dlx\", (it->first)[i]);\n" % (regBitWidth / 8 * 2) cppString += " printf(\": %d\\n\", it->second);\n" cppString += " }\n" cppString += "#endif\n" cppString += " printf(\"Number of unique results %lu out of %d\\n\", signatureMap.size(), EXECUTION_COUNT);\n" cppString += " fflush(stdout);\n" cppString += " return 0;\n" cppString += "}\n" cppFP = open(cppName, "w") cppFP.write(cppString) cppFP.close() def manager_common(headerName, dataName, dataBase, memLocs, bssName, bssBase, bssSizePerThread, cppName, threadList, signatureSize, regBitWidth, numExecutions, platform, strideType, verbosity): if (platform == "linuxpthread"): # Data section and BSS section generate_data_section(dataName, memLocs, strideType) if (verbosity > 0): print("Data binary file %s generated (base 0x%X, size %d)" % (dataName, dataBase, memLocs * 4)) bssSize = bssSizePerThread * len(threadList) generate_bss_section(bssName, bssSize) if (verbosity > 0): print("BSS binary file %s generated (base 0x%X, size %d)" % (bssName, bssBase, bssSize)) generate_test_manager(cppName, headerName, threadList, bssBase, bssSizePerThread, signatureSize, regBitWidth, numExecutions, strideType) if (verbosity > 0): print("Test manager %s generated" % (cppName)) #################################################################### # Compute signature size (maximum signature size across all threads) #################################################################### def
(intermediate, regBitWidth): maxSignatureFlushCount = 0 perthreadSignatureSizes = dict() for thread in intermediate: pathCount = 0 signatureFlushCount = 0 for intermediateCode in intermediate[thread]: if (intermediateCode["type"] == "profile"): # reg, targets if ((pathCount * len(intermediateCode["targets"])) > ((1 << regBitWidth) - 1)): pathCount = 0 signatureFlushCount += 1 if (pathCount == 0): pathCount = len(intermediateCode["targets"]) else: pathCount = pathCount * len(intermediateCode["targets"]) perthreadSignatureSizes[thread] = (signatureFlushCount + 1) * regBitWidth / 8 if (signatureFlushCount > maxSignatureFlushCount): maxSignatureFlushCount = signatureFlushCount # Number of bytes for each signature temp = (maxSignatureFlushCount + 1) * regBitWidth / 8 # Log2 ceiling function power2Boundary = 1 while (power2Boundary < temp): power2Boundary <<= 1 return [max(power2Boundary, regBitWidth / 8), perthreadSignatureSizes]
compute_max_signature_size
identifier_name
codegen_common.py
#!/usr/bin/python ########################################################################## # # MTraceCheck # Copyright 2017 The Regents of the University of Michigan # Doowon Lee and Valeria Bertacco # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ########################################################################## # # This file should be called from codegen.py # #################################################################### # Data section #################################################################### def generate_data_section(dataName, memLocs, strideType): assert(memLocs <= 0x10000) #dataArray = [] #for i in range(memLocs): # data = [i & 0xFF, (i >> 8) & 0xFF, 0xFF, 0xFF] # dataArray += data ## Data contents will be initialized in test manager, so just create a placeholder if (strideType == 0): dataArray = [0xFF for i in range(memLocs * 4 * 1)] elif (strideType == 1): dataArray = [0xFF for i in range(memLocs * 4 * 4)] elif (strideType == 2): dataArray = [0xFF for i in range(memLocs * 4 * 16)] else: assert(False) dataFP = open(dataName, "w") dataFP.write(bytearray(dataArray)) dataFP.close() #################################################################### # BSS section (section to be written by test threads) #################################################################### def generate_bss_section(bssName, bssSize): #bssArray = [] #for i in range(bssSize): # bssArray += [0x00] #bssFP = open(bssName, "w") #bssFP.write(bytearray(bssArray)) #bssFP.close() # Faster code bssFP = open(bssName, "wb") bssFP.seek(bssSize-1) bssFP.write("\0") bssFP.close() #################################################################### # Test manager CPP file #################################################################### def generate_test_manager(cppName, headerName, threadList, bssBase, bssSizePerThread, signatureSize, regBitWidth, numExecutions, strideType): # See an example of cpp file at exp/160815_test_manager/test_manager.cpp # (This example is possibly outdated) wordTypeString = "uint%d_t" % regBitWidth cppString = "" cppString += "#include <stdio.h>\n" cppString += "#include <stdlib.h>\n" cppString += "#include <stdint.h>\n" cppString += "#include <pthread.h>\n" cppString += "#include <map>\n" cppString += "#include <vector>\n" cppString += "#include \"%s\"\n" % headerName for thread in threadList: cppString += "extern \"C\" void* thread%d_routine(void*);\n" % thread cppString += "volatile int thread_spawn_lock = 0;\n" cppString += "#ifdef EXEC_SYNC\n" cppString += "volatile int thread_exec_barrier0 = 0;\n" cppString += "volatile int thread_exec_barrier1 = 0;\n" cppString += "volatile int thread_exec_barrier_ptr = 0;\n" cppString += "#endif\n" cppString += "int main()\n" cppString += "{\n" cppString += " int pthread_return;\n" cppString += " int numThreads = %d;\n" % len(threadList) cppString += " // Test BSS section initialization\n" cppString += " %s *bss_address = (%s *) TEST_BSS_SECTION;\n" % (wordTypeString, wordTypeString) cppString += " for (int i = 0; i < numThreads * TEST_BSS_SIZE_PER_THREAD; i += sizeof(%s)) {\n" % (wordTypeString) cppString += " *(bss_address++) = 0;\n" cppString += " }\n" cppString += " // Test data section initialization\n" cppString += " uint32_t *data_address= (uint32_t *) TEST_DATA_SECTION;\n" cppString += " for (int i = 0; i < NUM_SHARED_DATA; i++) {\n" cppString += " *data_address = (uint32_t) (0xFFFF0000 | i);\n" if (strideType == 0): cppString += " data_address++; // strideType = 0\n" elif (strideType == 1): cppString += " data_address+=4; // strideType = 1\n" elif (strideType == 2): cppString += " data_address+=16; // strideType = 2\n" else: assert(False) cppString += " }\n" cppString += " pthread_t* threads = (pthread_t *) malloc(sizeof(pthread_t) * numThreads);\n" for threadIndex in range(len(threadList)): cppString += " pthread_return = pthread_create(&threads[%d], NULL, thread%d_routine, NULL);\n" % (threadIndex, threadList[threadIndex]) cppString += " for (int t = 0; t < numThreads; t++)\n" cppString += " pthread_return = pthread_join(threads[t], NULL);\n" cppString += " std::map<std::vector<%s>, int> signatureMap;\n" % (wordTypeString) cppString += " std::vector<%s> resultVector;\n" % (wordTypeString) cppString += " %s *signature = (%s *) TEST_BSS_SECTION;\n" % (wordTypeString, wordTypeString) cppString += " for (int i = 0; i < EXECUTION_COUNT; i++) {\n" cppString += " resultVector.clear();\n" #cppString += "#ifndef NO_PRINT\n" cppString += "#if 0\n" cppString += " printf(\"%8d:\", i);\n" cppString += "#endif\n" cppString += " for (int t = 0; t < numThreads; t++) {\n" cppString += " for (int w = 0; w < SIGNATURE_SIZE_IN_WORD; w++) {\n" # NOTE: SIGNATURE WORD REORDERING #cppString += " for (int w = SIGNATURE_SIZE_IN_WORD - 1; w >= 0; w--) {\n" #cppString += " for (int t = 0; t < numThreads; t++) {\n" cppString += " %s address = (%s) signature + t * TEST_BSS_SIZE_PER_THREAD + w * sizeof(%s);\n" % (wordTypeString, wordTypeString, wordTypeString)
#cppString += " printf(\" 0x%%lx 0x%%0%dlx\", address, result);\n" % signatureSize cppString += "#endif\n" cppString += " }\n" cppString += " }\n" cppString += " if (signatureMap.find(resultVector) == signatureMap.end())\n" cppString += " signatureMap[resultVector] = 1;\n" cppString += " else\n" cppString += " signatureMap[resultVector]++;\n" #cppString += "#ifndef NO_PRINT\n" cppString += "#if 0\n" cppString += " printf(\"\\n\");\n" cppString += "#endif\n" cppString += " signature += SIGNATURE_SIZE_IN_WORD;\n" cppString += " }\n" cppString += "#ifndef NO_PRINT\n" cppString += " for (std::map<std::vector<%s>, int>::iterator it = signatureMap.begin(); it != signatureMap.end(); it++) {\n" % (wordTypeString) cppString += " for (int i = 0; i < (it->first).size(); i++)\n" cppString += " printf(\" 0x%%0%dlx\", (it->first)[i]);\n" % (regBitWidth / 8 * 2) cppString += " printf(\": %d\\n\", it->second);\n" cppString += " }\n" cppString += "#endif\n" cppString += " printf(\"Number of unique results %lu out of %d\\n\", signatureMap.size(), EXECUTION_COUNT);\n" cppString += " fflush(stdout);\n" cppString += " return 0;\n" cppString += "}\n" cppFP = open(cppName, "w") cppFP.write(cppString) cppFP.close() def manager_common(headerName, dataName, dataBase, memLocs, bssName, bssBase, bssSizePerThread, cppName, threadList, signatureSize, regBitWidth, numExecutions, platform, strideType, verbosity): if (platform == "linuxpthread"): # Data section and BSS section generate_data_section(dataName, memLocs, strideType) if (verbosity > 0): print("Data binary file %s generated (base 0x%X, size %d)" % (dataName, dataBase, memLocs * 4)) bssSize = bssSizePerThread * len(threadList) generate_bss_section(bssName, bssSize) if (verbosity > 0): print("BSS binary file %s generated (base 0x%X, size %d)" % (bssName, bssBase, bssSize)) generate_test_manager(cppName, headerName, threadList, bssBase, bssSizePerThread, signatureSize, regBitWidth, numExecutions, strideType) if (verbosity > 0): print("Test manager %s generated" % (cppName)) #################################################################### # Compute signature size (maximum signature size across all threads) #################################################################### def compute_max_signature_size(intermediate, regBitWidth): maxSignatureFlushCount = 0 perthreadSignatureSizes = dict() for thread in intermediate: pathCount = 0 signatureFlushCount = 0 for intermediateCode in intermediate[thread]: if (intermediateCode["type"] == "profile"): # reg, targets if ((pathCount * len(intermediateCode["targets"])) > ((1 << regBitWidth) - 1)): pathCount = 0 signatureFlushCount += 1 if (pathCount == 0): pathCount = len(intermediateCode["targets"]) else: pathCount = pathCount * len(intermediateCode["targets"]) perthreadSignatureSizes[thread] = (signatureFlushCount + 1) * regBitWidth / 8 if (signatureFlushCount > maxSignatureFlushCount): maxSignatureFlushCount = signatureFlushCount # Number of bytes for each signature temp = (maxSignatureFlushCount + 1) * regBitWidth / 8 # Log2 ceiling function power2Boundary = 1 while (power2Boundary < temp): power2Boundary <<= 1 return [max(power2Boundary, regBitWidth / 8), perthreadSignatureSizes]
cppString += " %s result = (%s)*(%s*)address;\n" % (wordTypeString, wordTypeString, wordTypeString) cppString += " resultVector.push_back(result);\n" #cppString += "#ifndef NO_PRINT\n" cppString += "#if 0\n" cppString += " printf(\" 0x%%0%dlx\", result);\n" % (regBitWidth / 8 * 2)
random_line_split
codegen_common.py
#!/usr/bin/python ########################################################################## # # MTraceCheck # Copyright 2017 The Regents of the University of Michigan # Doowon Lee and Valeria Bertacco # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ########################################################################## # # This file should be called from codegen.py # #################################################################### # Data section #################################################################### def generate_data_section(dataName, memLocs, strideType):
#################################################################### # BSS section (section to be written by test threads) #################################################################### def generate_bss_section(bssName, bssSize): #bssArray = [] #for i in range(bssSize): # bssArray += [0x00] #bssFP = open(bssName, "w") #bssFP.write(bytearray(bssArray)) #bssFP.close() # Faster code bssFP = open(bssName, "wb") bssFP.seek(bssSize-1) bssFP.write("\0") bssFP.close() #################################################################### # Test manager CPP file #################################################################### def generate_test_manager(cppName, headerName, threadList, bssBase, bssSizePerThread, signatureSize, regBitWidth, numExecutions, strideType): # See an example of cpp file at exp/160815_test_manager/test_manager.cpp # (This example is possibly outdated) wordTypeString = "uint%d_t" % regBitWidth cppString = "" cppString += "#include <stdio.h>\n" cppString += "#include <stdlib.h>\n" cppString += "#include <stdint.h>\n" cppString += "#include <pthread.h>\n" cppString += "#include <map>\n" cppString += "#include <vector>\n" cppString += "#include \"%s\"\n" % headerName for thread in threadList: cppString += "extern \"C\" void* thread%d_routine(void*);\n" % thread cppString += "volatile int thread_spawn_lock = 0;\n" cppString += "#ifdef EXEC_SYNC\n" cppString += "volatile int thread_exec_barrier0 = 0;\n" cppString += "volatile int thread_exec_barrier1 = 0;\n" cppString += "volatile int thread_exec_barrier_ptr = 0;\n" cppString += "#endif\n" cppString += "int main()\n" cppString += "{\n" cppString += " int pthread_return;\n" cppString += " int numThreads = %d;\n" % len(threadList) cppString += " // Test BSS section initialization\n" cppString += " %s *bss_address = (%s *) TEST_BSS_SECTION;\n" % (wordTypeString, wordTypeString) cppString += " for (int i = 0; i < numThreads * TEST_BSS_SIZE_PER_THREAD; i += sizeof(%s)) {\n" % (wordTypeString) cppString += " *(bss_address++) = 0;\n" cppString += " }\n" cppString += " // Test data section initialization\n" cppString += " uint32_t *data_address= (uint32_t *) TEST_DATA_SECTION;\n" cppString += " for (int i = 0; i < NUM_SHARED_DATA; i++) {\n" cppString += " *data_address = (uint32_t) (0xFFFF0000 | i);\n" if (strideType == 0): cppString += " data_address++; // strideType = 0\n" elif (strideType == 1): cppString += " data_address+=4; // strideType = 1\n" elif (strideType == 2): cppString += " data_address+=16; // strideType = 2\n" else: assert(False) cppString += " }\n" cppString += " pthread_t* threads = (pthread_t *) malloc(sizeof(pthread_t) * numThreads);\n" for threadIndex in range(len(threadList)): cppString += " pthread_return = pthread_create(&threads[%d], NULL, thread%d_routine, NULL);\n" % (threadIndex, threadList[threadIndex]) cppString += " for (int t = 0; t < numThreads; t++)\n" cppString += " pthread_return = pthread_join(threads[t], NULL);\n" cppString += " std::map<std::vector<%s>, int> signatureMap;\n" % (wordTypeString) cppString += " std::vector<%s> resultVector;\n" % (wordTypeString) cppString += " %s *signature = (%s *) TEST_BSS_SECTION;\n" % (wordTypeString, wordTypeString) cppString += " for (int i = 0; i < EXECUTION_COUNT; i++) {\n" cppString += " resultVector.clear();\n" #cppString += "#ifndef NO_PRINT\n" cppString += "#if 0\n" cppString += " printf(\"%8d:\", i);\n" cppString += "#endif\n" cppString += " for (int t = 0; t < numThreads; t++) {\n" cppString += " for (int w = 0; w < SIGNATURE_SIZE_IN_WORD; w++) {\n" # NOTE: SIGNATURE WORD REORDERING #cppString += " for (int w = SIGNATURE_SIZE_IN_WORD - 1; w >= 0; w--) {\n" #cppString += " for (int t = 0; t < numThreads; t++) {\n" cppString += " %s address = (%s) signature + t * TEST_BSS_SIZE_PER_THREAD + w * sizeof(%s);\n" % (wordTypeString, wordTypeString, wordTypeString) cppString += " %s result = (%s)*(%s*)address;\n" % (wordTypeString, wordTypeString, wordTypeString) cppString += " resultVector.push_back(result);\n" #cppString += "#ifndef NO_PRINT\n" cppString += "#if 0\n" cppString += " printf(\" 0x%%0%dlx\", result);\n" % (regBitWidth / 8 * 2) #cppString += " printf(\" 0x%%lx 0x%%0%dlx\", address, result);\n" % signatureSize cppString += "#endif\n" cppString += " }\n" cppString += " }\n" cppString += " if (signatureMap.find(resultVector) == signatureMap.end())\n" cppString += " signatureMap[resultVector] = 1;\n" cppString += " else\n" cppString += " signatureMap[resultVector]++;\n" #cppString += "#ifndef NO_PRINT\n" cppString += "#if 0\n" cppString += " printf(\"\\n\");\n" cppString += "#endif\n" cppString += " signature += SIGNATURE_SIZE_IN_WORD;\n" cppString += " }\n" cppString += "#ifndef NO_PRINT\n" cppString += " for (std::map<std::vector<%s>, int>::iterator it = signatureMap.begin(); it != signatureMap.end(); it++) {\n" % (wordTypeString) cppString += " for (int i = 0; i < (it->first).size(); i++)\n" cppString += " printf(\" 0x%%0%dlx\", (it->first)[i]);\n" % (regBitWidth / 8 * 2) cppString += " printf(\": %d\\n\", it->second);\n" cppString += " }\n" cppString += "#endif\n" cppString += " printf(\"Number of unique results %lu out of %d\\n\", signatureMap.size(), EXECUTION_COUNT);\n" cppString += " fflush(stdout);\n" cppString += " return 0;\n" cppString += "}\n" cppFP = open(cppName, "w") cppFP.write(cppString) cppFP.close() def manager_common(headerName, dataName, dataBase, memLocs, bssName, bssBase, bssSizePerThread, cppName, threadList, signatureSize, regBitWidth, numExecutions, platform, strideType, verbosity): if (platform == "linuxpthread"): # Data section and BSS section generate_data_section(dataName, memLocs, strideType) if (verbosity > 0): print("Data binary file %s generated (base 0x%X, size %d)" % (dataName, dataBase, memLocs * 4)) bssSize = bssSizePerThread * len(threadList) generate_bss_section(bssName, bssSize) if (verbosity > 0): print("BSS binary file %s generated (base 0x%X, size %d)" % (bssName, bssBase, bssSize)) generate_test_manager(cppName, headerName, threadList, bssBase, bssSizePerThread, signatureSize, regBitWidth, numExecutions, strideType) if (verbosity > 0): print("Test manager %s generated" % (cppName)) #################################################################### # Compute signature size (maximum signature size across all threads) #################################################################### def compute_max_signature_size(intermediate, regBitWidth): maxSignatureFlushCount = 0 perthreadSignatureSizes = dict() for thread in intermediate: pathCount = 0 signatureFlushCount = 0 for intermediateCode in intermediate[thread]: if (intermediateCode["type"] == "profile"): # reg, targets if ((pathCount * len(intermediateCode["targets"])) > ((1 << regBitWidth) - 1)): pathCount = 0 signatureFlushCount += 1 if (pathCount == 0): pathCount = len(intermediateCode["targets"]) else: pathCount = pathCount * len(intermediateCode["targets"]) perthreadSignatureSizes[thread] = (signatureFlushCount + 1) * regBitWidth / 8 if (signatureFlushCount > maxSignatureFlushCount): maxSignatureFlushCount = signatureFlushCount # Number of bytes for each signature temp = (maxSignatureFlushCount + 1) * regBitWidth / 8 # Log2 ceiling function power2Boundary = 1 while (power2Boundary < temp): power2Boundary <<= 1 return [max(power2Boundary, regBitWidth / 8), perthreadSignatureSizes]
assert(memLocs <= 0x10000) #dataArray = [] #for i in range(memLocs): # data = [i & 0xFF, (i >> 8) & 0xFF, 0xFF, 0xFF] # dataArray += data ## Data contents will be initialized in test manager, so just create a placeholder if (strideType == 0): dataArray = [0xFF for i in range(memLocs * 4 * 1)] elif (strideType == 1): dataArray = [0xFF for i in range(memLocs * 4 * 4)] elif (strideType == 2): dataArray = [0xFF for i in range(memLocs * 4 * 16)] else: assert(False) dataFP = open(dataName, "w") dataFP.write(bytearray(dataArray)) dataFP.close()
identifier_body
codegen_common.py
#!/usr/bin/python ########################################################################## # # MTraceCheck # Copyright 2017 The Regents of the University of Michigan # Doowon Lee and Valeria Bertacco # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ########################################################################## # # This file should be called from codegen.py # #################################################################### # Data section #################################################################### def generate_data_section(dataName, memLocs, strideType): assert(memLocs <= 0x10000) #dataArray = [] #for i in range(memLocs): # data = [i & 0xFF, (i >> 8) & 0xFF, 0xFF, 0xFF] # dataArray += data ## Data contents will be initialized in test manager, so just create a placeholder if (strideType == 0): dataArray = [0xFF for i in range(memLocs * 4 * 1)] elif (strideType == 1): dataArray = [0xFF for i in range(memLocs * 4 * 4)] elif (strideType == 2): dataArray = [0xFF for i in range(memLocs * 4 * 16)] else: assert(False) dataFP = open(dataName, "w") dataFP.write(bytearray(dataArray)) dataFP.close() #################################################################### # BSS section (section to be written by test threads) #################################################################### def generate_bss_section(bssName, bssSize): #bssArray = [] #for i in range(bssSize): # bssArray += [0x00] #bssFP = open(bssName, "w") #bssFP.write(bytearray(bssArray)) #bssFP.close() # Faster code bssFP = open(bssName, "wb") bssFP.seek(bssSize-1) bssFP.write("\0") bssFP.close() #################################################################### # Test manager CPP file #################################################################### def generate_test_manager(cppName, headerName, threadList, bssBase, bssSizePerThread, signatureSize, regBitWidth, numExecutions, strideType): # See an example of cpp file at exp/160815_test_manager/test_manager.cpp # (This example is possibly outdated) wordTypeString = "uint%d_t" % regBitWidth cppString = "" cppString += "#include <stdio.h>\n" cppString += "#include <stdlib.h>\n" cppString += "#include <stdint.h>\n" cppString += "#include <pthread.h>\n" cppString += "#include <map>\n" cppString += "#include <vector>\n" cppString += "#include \"%s\"\n" % headerName for thread in threadList: cppString += "extern \"C\" void* thread%d_routine(void*);\n" % thread cppString += "volatile int thread_spawn_lock = 0;\n" cppString += "#ifdef EXEC_SYNC\n" cppString += "volatile int thread_exec_barrier0 = 0;\n" cppString += "volatile int thread_exec_barrier1 = 0;\n" cppString += "volatile int thread_exec_barrier_ptr = 0;\n" cppString += "#endif\n" cppString += "int main()\n" cppString += "{\n" cppString += " int pthread_return;\n" cppString += " int numThreads = %d;\n" % len(threadList) cppString += " // Test BSS section initialization\n" cppString += " %s *bss_address = (%s *) TEST_BSS_SECTION;\n" % (wordTypeString, wordTypeString) cppString += " for (int i = 0; i < numThreads * TEST_BSS_SIZE_PER_THREAD; i += sizeof(%s)) {\n" % (wordTypeString) cppString += " *(bss_address++) = 0;\n" cppString += " }\n" cppString += " // Test data section initialization\n" cppString += " uint32_t *data_address= (uint32_t *) TEST_DATA_SECTION;\n" cppString += " for (int i = 0; i < NUM_SHARED_DATA; i++) {\n" cppString += " *data_address = (uint32_t) (0xFFFF0000 | i);\n" if (strideType == 0): cppString += " data_address++; // strideType = 0\n" elif (strideType == 1): cppString += " data_address+=4; // strideType = 1\n" elif (strideType == 2): cppString += " data_address+=16; // strideType = 2\n" else: assert(False) cppString += " }\n" cppString += " pthread_t* threads = (pthread_t *) malloc(sizeof(pthread_t) * numThreads);\n" for threadIndex in range(len(threadList)): cppString += " pthread_return = pthread_create(&threads[%d], NULL, thread%d_routine, NULL);\n" % (threadIndex, threadList[threadIndex]) cppString += " for (int t = 0; t < numThreads; t++)\n" cppString += " pthread_return = pthread_join(threads[t], NULL);\n" cppString += " std::map<std::vector<%s>, int> signatureMap;\n" % (wordTypeString) cppString += " std::vector<%s> resultVector;\n" % (wordTypeString) cppString += " %s *signature = (%s *) TEST_BSS_SECTION;\n" % (wordTypeString, wordTypeString) cppString += " for (int i = 0; i < EXECUTION_COUNT; i++) {\n" cppString += " resultVector.clear();\n" #cppString += "#ifndef NO_PRINT\n" cppString += "#if 0\n" cppString += " printf(\"%8d:\", i);\n" cppString += "#endif\n" cppString += " for (int t = 0; t < numThreads; t++) {\n" cppString += " for (int w = 0; w < SIGNATURE_SIZE_IN_WORD; w++) {\n" # NOTE: SIGNATURE WORD REORDERING #cppString += " for (int w = SIGNATURE_SIZE_IN_WORD - 1; w >= 0; w--) {\n" #cppString += " for (int t = 0; t < numThreads; t++) {\n" cppString += " %s address = (%s) signature + t * TEST_BSS_SIZE_PER_THREAD + w * sizeof(%s);\n" % (wordTypeString, wordTypeString, wordTypeString) cppString += " %s result = (%s)*(%s*)address;\n" % (wordTypeString, wordTypeString, wordTypeString) cppString += " resultVector.push_back(result);\n" #cppString += "#ifndef NO_PRINT\n" cppString += "#if 0\n" cppString += " printf(\" 0x%%0%dlx\", result);\n" % (regBitWidth / 8 * 2) #cppString += " printf(\" 0x%%lx 0x%%0%dlx\", address, result);\n" % signatureSize cppString += "#endif\n" cppString += " }\n" cppString += " }\n" cppString += " if (signatureMap.find(resultVector) == signatureMap.end())\n" cppString += " signatureMap[resultVector] = 1;\n" cppString += " else\n" cppString += " signatureMap[resultVector]++;\n" #cppString += "#ifndef NO_PRINT\n" cppString += "#if 0\n" cppString += " printf(\"\\n\");\n" cppString += "#endif\n" cppString += " signature += SIGNATURE_SIZE_IN_WORD;\n" cppString += " }\n" cppString += "#ifndef NO_PRINT\n" cppString += " for (std::map<std::vector<%s>, int>::iterator it = signatureMap.begin(); it != signatureMap.end(); it++) {\n" % (wordTypeString) cppString += " for (int i = 0; i < (it->first).size(); i++)\n" cppString += " printf(\" 0x%%0%dlx\", (it->first)[i]);\n" % (regBitWidth / 8 * 2) cppString += " printf(\": %d\\n\", it->second);\n" cppString += " }\n" cppString += "#endif\n" cppString += " printf(\"Number of unique results %lu out of %d\\n\", signatureMap.size(), EXECUTION_COUNT);\n" cppString += " fflush(stdout);\n" cppString += " return 0;\n" cppString += "}\n" cppFP = open(cppName, "w") cppFP.write(cppString) cppFP.close() def manager_common(headerName, dataName, dataBase, memLocs, bssName, bssBase, bssSizePerThread, cppName, threadList, signatureSize, regBitWidth, numExecutions, platform, strideType, verbosity): if (platform == "linuxpthread"): # Data section and BSS section generate_data_section(dataName, memLocs, strideType) if (verbosity > 0): print("Data binary file %s generated (base 0x%X, size %d)" % (dataName, dataBase, memLocs * 4)) bssSize = bssSizePerThread * len(threadList) generate_bss_section(bssName, bssSize) if (verbosity > 0): print("BSS binary file %s generated (base 0x%X, size %d)" % (bssName, bssBase, bssSize)) generate_test_manager(cppName, headerName, threadList, bssBase, bssSizePerThread, signatureSize, regBitWidth, numExecutions, strideType) if (verbosity > 0): print("Test manager %s generated" % (cppName)) #################################################################### # Compute signature size (maximum signature size across all threads) #################################################################### def compute_max_signature_size(intermediate, regBitWidth): maxSignatureFlushCount = 0 perthreadSignatureSizes = dict() for thread in intermediate: pathCount = 0 signatureFlushCount = 0 for intermediateCode in intermediate[thread]:
perthreadSignatureSizes[thread] = (signatureFlushCount + 1) * regBitWidth / 8 if (signatureFlushCount > maxSignatureFlushCount): maxSignatureFlushCount = signatureFlushCount # Number of bytes for each signature temp = (maxSignatureFlushCount + 1) * regBitWidth / 8 # Log2 ceiling function power2Boundary = 1 while (power2Boundary < temp): power2Boundary <<= 1 return [max(power2Boundary, regBitWidth / 8), perthreadSignatureSizes]
if (intermediateCode["type"] == "profile"): # reg, targets if ((pathCount * len(intermediateCode["targets"])) > ((1 << regBitWidth) - 1)): pathCount = 0 signatureFlushCount += 1 if (pathCount == 0): pathCount = len(intermediateCode["targets"]) else: pathCount = pathCount * len(intermediateCode["targets"])
conditional_block
queue.py
"""Queue implementation using Linked list.""" from __future__ import print_function from linked_list import Linked_List, Node class
(Linked_List): def __init__(self): Linked_List.__init__(self) def enqueue(self, item): node = Node(item) self.insert_front(node) def dequeue(self): return self.remove_end() def is_empty(self): return self.count == 0 def size(self): return self.count def test_queue(): print("\n\n QUEUE TESTING") queue = Queue() print("Queue Empty?", queue.is_empty()) queue.enqueue("A") queue.enqueue("B") queue.enqueue("C") print("Queue Size:", queue.size()) print(queue) print("DEQUEUEING 1") print(queue.dequeue()) print(queue) print("Queue Size:", queue.size()) print("DEQUEUEING 2") print(queue.dequeue()) print(queue) print("Queue Size:", queue.size()) print("Queue Empty?", queue.is_empty()) print("DEQUEUEING 3") print(queue.dequeue()) print(queue) print("Queue Size:", queue.size()) print("Queue Empty?", queue.is_empty()) print(queue) print("DEQUEUEING 4") print(queue.dequeue()) if __name__ == '__main__': test_queue()
Queue
identifier_name
queue.py
"""Queue implementation using Linked list."""
def __init__(self): Linked_List.__init__(self) def enqueue(self, item): node = Node(item) self.insert_front(node) def dequeue(self): return self.remove_end() def is_empty(self): return self.count == 0 def size(self): return self.count def test_queue(): print("\n\n QUEUE TESTING") queue = Queue() print("Queue Empty?", queue.is_empty()) queue.enqueue("A") queue.enqueue("B") queue.enqueue("C") print("Queue Size:", queue.size()) print(queue) print("DEQUEUEING 1") print(queue.dequeue()) print(queue) print("Queue Size:", queue.size()) print("DEQUEUEING 2") print(queue.dequeue()) print(queue) print("Queue Size:", queue.size()) print("Queue Empty?", queue.is_empty()) print("DEQUEUEING 3") print(queue.dequeue()) print(queue) print("Queue Size:", queue.size()) print("Queue Empty?", queue.is_empty()) print(queue) print("DEQUEUEING 4") print(queue.dequeue()) if __name__ == '__main__': test_queue()
from __future__ import print_function from linked_list import Linked_List, Node class Queue(Linked_List):
random_line_split
queue.py
"""Queue implementation using Linked list.""" from __future__ import print_function from linked_list import Linked_List, Node class Queue(Linked_List): def __init__(self): Linked_List.__init__(self) def enqueue(self, item): node = Node(item) self.insert_front(node) def dequeue(self): return self.remove_end() def is_empty(self): return self.count == 0 def size(self): return self.count def test_queue(): print("\n\n QUEUE TESTING") queue = Queue() print("Queue Empty?", queue.is_empty()) queue.enqueue("A") queue.enqueue("B") queue.enqueue("C") print("Queue Size:", queue.size()) print(queue) print("DEQUEUEING 1") print(queue.dequeue()) print(queue) print("Queue Size:", queue.size()) print("DEQUEUEING 2") print(queue.dequeue()) print(queue) print("Queue Size:", queue.size()) print("Queue Empty?", queue.is_empty()) print("DEQUEUEING 3") print(queue.dequeue()) print(queue) print("Queue Size:", queue.size()) print("Queue Empty?", queue.is_empty()) print(queue) print("DEQUEUEING 4") print(queue.dequeue()) if __name__ == '__main__':
test_queue()
conditional_block
queue.py
"""Queue implementation using Linked list.""" from __future__ import print_function from linked_list import Linked_List, Node class Queue(Linked_List): def __init__(self): Linked_List.__init__(self) def enqueue(self, item): node = Node(item) self.insert_front(node) def dequeue(self): return self.remove_end() def is_empty(self):
def size(self): return self.count def test_queue(): print("\n\n QUEUE TESTING") queue = Queue() print("Queue Empty?", queue.is_empty()) queue.enqueue("A") queue.enqueue("B") queue.enqueue("C") print("Queue Size:", queue.size()) print(queue) print("DEQUEUEING 1") print(queue.dequeue()) print(queue) print("Queue Size:", queue.size()) print("DEQUEUEING 2") print(queue.dequeue()) print(queue) print("Queue Size:", queue.size()) print("Queue Empty?", queue.is_empty()) print("DEQUEUEING 3") print(queue.dequeue()) print(queue) print("Queue Size:", queue.size()) print("Queue Empty?", queue.is_empty()) print(queue) print("DEQUEUEING 4") print(queue.dequeue()) if __name__ == '__main__': test_queue()
return self.count == 0
identifier_body
setup.py
from setuptools import setup#, find_packages, Extension import distutils.command.build as _build import setuptools.command.install as _install import sys import os import os.path as op import distutils.spawn as ds import distutils.dir_util as dd import posixpath def run_cmake(arg=""): """ Forcing to run cmake """ if ds.find_executable('cmake') is None: print "CMake is required to build zql" print "Please install cmake version >= 2.8 and re-run setup" sys.exit(-1) print "Configuring zql build with CMake.... " cmake_args = arg try: build_dir = op.join(op.split(__file__)[0], 'build') dd.mkpath(build_dir) os.chdir("build") ds.spawn(['cmake', '..'] + cmake_args.split()) ds.spawn(['make', 'clean']) ds.spawn(['make']) os.chdir("..") except ds.DistutilsExecError: print "Error while running cmake" print "run 'setup.py build --help' for build options" print "You may also try editing the settings in CMakeLists.txt file and re-running setup" sys.exit(-1) class build(_build.build): def
(self): run_cmake() # Now populate the extension module attribute. #self.distribution.ext_modules = get_ext_modules() _build.build.run(self) class install(_install.install): def run(self): if not posixpath.exists("src/zq.so"): run_cmake() ds.spawn(['make', 'install']) #self.distribution.ext_modules = get_ext_modules() self.do_egg_install() with open('README.txt') as file: clips6_long_desc = file.read() setup( name = "zq", version = '0.6', description = 'ZQL - Zabbix Query Language', install_requires = ["cython", "msgpack-python", "simplejson", "hy", "pyfiglet", "gevent", "json", "termcolor", "humanfriendly", "ipaddr", "pyfscache", "Cheetah", "dateparser", "pygithub", ], requires = [], include_package_data = True, url = 'https://github.com/vulogov/zq/', author='Vladimir Ulogov', author_email = 'vladimir.ulogov@me.com', maintainer_email = 'vladimir.ulogov@me.com', license = "GNU GPL Versin 3", long_description = clips6_long_desc, keywords = "zql, monitoring, zabbix", platforms = ['GNU/Linux','Unix','Mac OS-X'], classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Monitoring', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', 'Environment :: Console', 'Environment :: Console :: Curses' ], # ext_modules is not present here. This will be generated through CMake via the # build or install commands cmdclass={'install':install,'build': build}, zip_safe=False, packages = ['zq'], package_data = { 'zq': ['zq.so', '*.pyx', '*.pyi'] } )
run
identifier_name
setup.py
from setuptools import setup#, find_packages, Extension import distutils.command.build as _build import setuptools.command.install as _install import sys import os import os.path as op import distutils.spawn as ds import distutils.dir_util as dd import posixpath def run_cmake(arg=""): """ Forcing to run cmake """ if ds.find_executable('cmake') is None: print "CMake is required to build zql" print "Please install cmake version >= 2.8 and re-run setup" sys.exit(-1) print "Configuring zql build with CMake.... " cmake_args = arg try: build_dir = op.join(op.split(__file__)[0], 'build') dd.mkpath(build_dir) os.chdir("build") ds.spawn(['cmake', '..'] + cmake_args.split()) ds.spawn(['make', 'clean']) ds.spawn(['make']) os.chdir("..") except ds.DistutilsExecError: print "Error while running cmake" print "run 'setup.py build --help' for build options" print "You may also try editing the settings in CMakeLists.txt file and re-running setup" sys.exit(-1) class build(_build.build): def run(self): run_cmake() # Now populate the extension module attribute. #self.distribution.ext_modules = get_ext_modules() _build.build.run(self) class install(_install.install): def run(self): if not posixpath.exists("src/zq.so"):
ds.spawn(['make', 'install']) #self.distribution.ext_modules = get_ext_modules() self.do_egg_install() with open('README.txt') as file: clips6_long_desc = file.read() setup( name = "zq", version = '0.6', description = 'ZQL - Zabbix Query Language', install_requires = ["cython", "msgpack-python", "simplejson", "hy", "pyfiglet", "gevent", "json", "termcolor", "humanfriendly", "ipaddr", "pyfscache", "Cheetah", "dateparser", "pygithub", ], requires = [], include_package_data = True, url = 'https://github.com/vulogov/zq/', author='Vladimir Ulogov', author_email = 'vladimir.ulogov@me.com', maintainer_email = 'vladimir.ulogov@me.com', license = "GNU GPL Versin 3", long_description = clips6_long_desc, keywords = "zql, monitoring, zabbix", platforms = ['GNU/Linux','Unix','Mac OS-X'], classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Monitoring', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', 'Environment :: Console', 'Environment :: Console :: Curses' ], # ext_modules is not present here. This will be generated through CMake via the # build or install commands cmdclass={'install':install,'build': build}, zip_safe=False, packages = ['zq'], package_data = { 'zq': ['zq.so', '*.pyx', '*.pyi'] } )
run_cmake()
conditional_block
setup.py
from setuptools import setup#, find_packages, Extension import distutils.command.build as _build import setuptools.command.install as _install import sys import os import os.path as op import distutils.spawn as ds import distutils.dir_util as dd import posixpath def run_cmake(arg=""): """ Forcing to run cmake """ if ds.find_executable('cmake') is None: print "CMake is required to build zql" print "Please install cmake version >= 2.8 and re-run setup" sys.exit(-1) print "Configuring zql build with CMake.... " cmake_args = arg try: build_dir = op.join(op.split(__file__)[0], 'build') dd.mkpath(build_dir) os.chdir("build") ds.spawn(['cmake', '..'] + cmake_args.split()) ds.spawn(['make', 'clean']) ds.spawn(['make']) os.chdir("..") except ds.DistutilsExecError: print "Error while running cmake" print "run 'setup.py build --help' for build options" print "You may also try editing the settings in CMakeLists.txt file and re-running setup" sys.exit(-1) class build(_build.build):
class install(_install.install): def run(self): if not posixpath.exists("src/zq.so"): run_cmake() ds.spawn(['make', 'install']) #self.distribution.ext_modules = get_ext_modules() self.do_egg_install() with open('README.txt') as file: clips6_long_desc = file.read() setup( name = "zq", version = '0.6', description = 'ZQL - Zabbix Query Language', install_requires = ["cython", "msgpack-python", "simplejson", "hy", "pyfiglet", "gevent", "json", "termcolor", "humanfriendly", "ipaddr", "pyfscache", "Cheetah", "dateparser", "pygithub", ], requires = [], include_package_data = True, url = 'https://github.com/vulogov/zq/', author='Vladimir Ulogov', author_email = 'vladimir.ulogov@me.com', maintainer_email = 'vladimir.ulogov@me.com', license = "GNU GPL Versin 3", long_description = clips6_long_desc, keywords = "zql, monitoring, zabbix", platforms = ['GNU/Linux','Unix','Mac OS-X'], classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Monitoring', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', 'Environment :: Console', 'Environment :: Console :: Curses' ], # ext_modules is not present here. This will be generated through CMake via the # build or install commands cmdclass={'install':install,'build': build}, zip_safe=False, packages = ['zq'], package_data = { 'zq': ['zq.so', '*.pyx', '*.pyi'] } )
def run(self): run_cmake() # Now populate the extension module attribute. #self.distribution.ext_modules = get_ext_modules() _build.build.run(self)
identifier_body
setup.py
from setuptools import setup#, find_packages, Extension import distutils.command.build as _build import setuptools.command.install as _install import sys import os import os.path as op import distutils.spawn as ds import distutils.dir_util as dd import posixpath def run_cmake(arg=""): """ Forcing to run cmake """ if ds.find_executable('cmake') is None: print "CMake is required to build zql" print "Please install cmake version >= 2.8 and re-run setup" sys.exit(-1) print "Configuring zql build with CMake.... " cmake_args = arg try: build_dir = op.join(op.split(__file__)[0], 'build') dd.mkpath(build_dir) os.chdir("build") ds.spawn(['cmake', '..'] + cmake_args.split()) ds.spawn(['make', 'clean']) ds.spawn(['make']) os.chdir("..") except ds.DistutilsExecError: print "Error while running cmake" print "run 'setup.py build --help' for build options" print "You may also try editing the settings in CMakeLists.txt file and re-running setup" sys.exit(-1) class build(_build.build): def run(self): run_cmake() # Now populate the extension module attribute. #self.distribution.ext_modules = get_ext_modules() _build.build.run(self) class install(_install.install): def run(self): if not posixpath.exists("src/zq.so"): run_cmake() ds.spawn(['make', 'install']) #self.distribution.ext_modules = get_ext_modules() self.do_egg_install() with open('README.txt') as file: clips6_long_desc = file.read() setup( name = "zq", version = '0.6', description = 'ZQL - Zabbix Query Language', install_requires = ["cython", "msgpack-python", "simplejson", "hy", "pyfiglet", "gevent", "json", "termcolor", "humanfriendly", "ipaddr", "pyfscache", "Cheetah", "dateparser", "pygithub", ], requires = [], include_package_data = True, url = 'https://github.com/vulogov/zq/', author='Vladimir Ulogov', author_email = 'vladimir.ulogov@me.com', maintainer_email = 'vladimir.ulogov@me.com', license = "GNU GPL Versin 3", long_description = clips6_long_desc, keywords = "zql, monitoring, zabbix", platforms = ['GNU/Linux','Unix','Mac OS-X'], classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Monitoring', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', 'Environment :: Console',
], # ext_modules is not present here. This will be generated through CMake via the # build or install commands cmdclass={'install':install,'build': build}, zip_safe=False, packages = ['zq'], package_data = { 'zq': ['zq.so', '*.pyx', '*.pyi'] } )
'Environment :: Console :: Curses'
random_line_split
compress.rs
use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use ::image; use ::image::GenericImage; use dct; use quantize; use color_space; use compressed_image; use protobuf::Message;
use flate2::Compression; use flate2::write::ZlibEncoder; pub fn compress_file(input_filename: &Path) { let file_stem = match input_filename.file_stem() { Some(stem) => stem, None => panic!("Invalid input filename: Could not automatically determine output file"), }; let file_container = match input_filename.parent() { Some(result) => result, None => { panic!("Invalid input filename: Could not automatically determine the output file \ directory") } }; let mut output_filename = PathBuf::from(&file_container); output_filename.push(file_stem); output_filename.set_extension("msca"); compress_file_to_output(input_filename, output_filename.as_path()); } pub fn compress_file_to_output(input_filename: &Path, output_filename: &Path) { if let Some(extension) = output_filename.extension() { assert!(extension == "msca", "Output file for compression must be 'msca'") } else { panic!("Output file for compression must be msca") } let input_image = image::open(input_filename).unwrap(); let mut output_file = File::create(&Path::new(&output_filename)).unwrap(); compress(&input_image, &mut output_file); } fn compress(input_image: &image::DynamicImage, output: &mut File) { let (width, height) = input_image.dimensions(); let mut red_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize); let mut green_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize); let mut blue_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize); // split the color data into channels for y in 0..height { for x in 0..width { let pixel = input_image.get_pixel(x, y); let (y, cb, cr) = color_space::rgb_to_ycbcr(pixel[0], pixel[1], pixel[2]); red_channel.push(y); green_channel.push(cb); blue_channel.push(cr); } } let mut serializer = compressed_image::compressed_image::new(); serializer.set_width(width); serializer.set_height(height); // compress the data and put it directly into the serializer serializer.set_red(compress_color_channel(width as usize, height as usize, red_channel)); serializer.set_green(compress_color_channel(width as usize, height as usize, green_channel)); serializer.set_blue(compress_color_channel(width as usize, height as usize, blue_channel)); let serialized_bytes = serializer.write_to_bytes().unwrap(); // losslessly compress the serialized data let mut enc = ZlibEncoder::new(output, Compression::Default); let mut written = 0; while written < serialized_bytes.len() { written += enc.write(&serialized_bytes[written..serialized_bytes.len()]).unwrap(); } let _ = enc.finish(); } fn compress_color_channel(width: usize, height: usize, mut uncompressed_channel_data: Vec<f32>) -> Vec<i32> { dct::dct2_2d(width, height, &mut uncompressed_channel_data); quantize::encode(width, height, &uncompressed_channel_data) }
random_line_split
compress.rs
use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use ::image; use ::image::GenericImage; use dct; use quantize; use color_space; use compressed_image; use protobuf::Message; use flate2::Compression; use flate2::write::ZlibEncoder; pub fn compress_file(input_filename: &Path) { let file_stem = match input_filename.file_stem() { Some(stem) => stem, None => panic!("Invalid input filename: Could not automatically determine output file"), }; let file_container = match input_filename.parent() { Some(result) => result, None => { panic!("Invalid input filename: Could not automatically determine the output file \ directory") } }; let mut output_filename = PathBuf::from(&file_container); output_filename.push(file_stem); output_filename.set_extension("msca"); compress_file_to_output(input_filename, output_filename.as_path()); } pub fn compress_file_to_output(input_filename: &Path, output_filename: &Path) { if let Some(extension) = output_filename.extension() { assert!(extension == "msca", "Output file for compression must be 'msca'") } else { panic!("Output file for compression must be msca") } let input_image = image::open(input_filename).unwrap(); let mut output_file = File::create(&Path::new(&output_filename)).unwrap(); compress(&input_image, &mut output_file); } fn compress(input_image: &image::DynamicImage, output: &mut File) { let (width, height) = input_image.dimensions(); let mut red_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize); let mut green_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize); let mut blue_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize); // split the color data into channels for y in 0..height { for x in 0..width { let pixel = input_image.get_pixel(x, y); let (y, cb, cr) = color_space::rgb_to_ycbcr(pixel[0], pixel[1], pixel[2]); red_channel.push(y); green_channel.push(cb); blue_channel.push(cr); } } let mut serializer = compressed_image::compressed_image::new(); serializer.set_width(width); serializer.set_height(height); // compress the data and put it directly into the serializer serializer.set_red(compress_color_channel(width as usize, height as usize, red_channel)); serializer.set_green(compress_color_channel(width as usize, height as usize, green_channel)); serializer.set_blue(compress_color_channel(width as usize, height as usize, blue_channel)); let serialized_bytes = serializer.write_to_bytes().unwrap(); // losslessly compress the serialized data let mut enc = ZlibEncoder::new(output, Compression::Default); let mut written = 0; while written < serialized_bytes.len() { written += enc.write(&serialized_bytes[written..serialized_bytes.len()]).unwrap(); } let _ = enc.finish(); } fn compress_color_channel(width: usize, height: usize, mut uncompressed_channel_data: Vec<f32>) -> Vec<i32>
{ dct::dct2_2d(width, height, &mut uncompressed_channel_data); quantize::encode(width, height, &uncompressed_channel_data) }
identifier_body
compress.rs
use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use ::image; use ::image::GenericImage; use dct; use quantize; use color_space; use compressed_image; use protobuf::Message; use flate2::Compression; use flate2::write::ZlibEncoder; pub fn compress_file(input_filename: &Path) { let file_stem = match input_filename.file_stem() { Some(stem) => stem, None => panic!("Invalid input filename: Could not automatically determine output file"), }; let file_container = match input_filename.parent() { Some(result) => result, None => { panic!("Invalid input filename: Could not automatically determine the output file \ directory") } }; let mut output_filename = PathBuf::from(&file_container); output_filename.push(file_stem); output_filename.set_extension("msca"); compress_file_to_output(input_filename, output_filename.as_path()); } pub fn
(input_filename: &Path, output_filename: &Path) { if let Some(extension) = output_filename.extension() { assert!(extension == "msca", "Output file for compression must be 'msca'") } else { panic!("Output file for compression must be msca") } let input_image = image::open(input_filename).unwrap(); let mut output_file = File::create(&Path::new(&output_filename)).unwrap(); compress(&input_image, &mut output_file); } fn compress(input_image: &image::DynamicImage, output: &mut File) { let (width, height) = input_image.dimensions(); let mut red_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize); let mut green_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize); let mut blue_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize); // split the color data into channels for y in 0..height { for x in 0..width { let pixel = input_image.get_pixel(x, y); let (y, cb, cr) = color_space::rgb_to_ycbcr(pixel[0], pixel[1], pixel[2]); red_channel.push(y); green_channel.push(cb); blue_channel.push(cr); } } let mut serializer = compressed_image::compressed_image::new(); serializer.set_width(width); serializer.set_height(height); // compress the data and put it directly into the serializer serializer.set_red(compress_color_channel(width as usize, height as usize, red_channel)); serializer.set_green(compress_color_channel(width as usize, height as usize, green_channel)); serializer.set_blue(compress_color_channel(width as usize, height as usize, blue_channel)); let serialized_bytes = serializer.write_to_bytes().unwrap(); // losslessly compress the serialized data let mut enc = ZlibEncoder::new(output, Compression::Default); let mut written = 0; while written < serialized_bytes.len() { written += enc.write(&serialized_bytes[written..serialized_bytes.len()]).unwrap(); } let _ = enc.finish(); } fn compress_color_channel(width: usize, height: usize, mut uncompressed_channel_data: Vec<f32>) -> Vec<i32> { dct::dct2_2d(width, height, &mut uncompressed_channel_data); quantize::encode(width, height, &uncompressed_channel_data) }
compress_file_to_output
identifier_name
chal-new.js
function load_chal_template(chal_type_name)
nonce = "{{ nonce }}"; $.get(script_root + '/admin/chal_types', function(data){ console.log(data); $("#create-chals-select").empty(); var chal_type_amt = Object.keys(data).length; if (chal_type_amt > 1){ var option = "<option> -- </option>"; $("#create-chals-select").append(option); for (var key in data){ var option = "<option value='{0}'>{1}</option>".format(key, data[key]); $("#create-chals-select").append(option); } } else if (chal_type_amt == 1) { var key = Object.keys(data)[0]; $("#create-chals-select").parent().parent().parent().empty(); load_chal_template(data[key]); } }); $('#create-chals-select').change(function(){ var chal_type_name = $(this).find("option:selected").text(); load_chal_template(chal_type_name); });
{ $.get(script_root + '/static/admin/js/templates/challenges/'+ chal_type_name +'/' + chal_type_name + '-challenge-create.hbs', function(template_data){ var template = Handlebars.compile(template_data); $("#create-chal-entry-div").html(template({'nonce':nonce, 'script_root':script_root})); $.getScript(script_root + '/static/admin/js/templates/challenges/'+chal_type_name+'/'+chal_type_name+'-challenge-create.js', function(){ console.log('loaded'); }); }); }
identifier_body
chal-new.js
function
(chal_type_name){ $.get(script_root + '/static/admin/js/templates/challenges/'+ chal_type_name +'/' + chal_type_name + '-challenge-create.hbs', function(template_data){ var template = Handlebars.compile(template_data); $("#create-chal-entry-div").html(template({'nonce':nonce, 'script_root':script_root})); $.getScript(script_root + '/static/admin/js/templates/challenges/'+chal_type_name+'/'+chal_type_name+'-challenge-create.js', function(){ console.log('loaded'); }); }); } nonce = "{{ nonce }}"; $.get(script_root + '/admin/chal_types', function(data){ console.log(data); $("#create-chals-select").empty(); var chal_type_amt = Object.keys(data).length; if (chal_type_amt > 1){ var option = "<option> -- </option>"; $("#create-chals-select").append(option); for (var key in data){ var option = "<option value='{0}'>{1}</option>".format(key, data[key]); $("#create-chals-select").append(option); } } else if (chal_type_amt == 1) { var key = Object.keys(data)[0]; $("#create-chals-select").parent().parent().parent().empty(); load_chal_template(data[key]); } }); $('#create-chals-select').change(function(){ var chal_type_name = $(this).find("option:selected").text(); load_chal_template(chal_type_name); });
load_chal_template
identifier_name
chal-new.js
function load_chal_template(chal_type_name){ $.get(script_root + '/static/admin/js/templates/challenges/'+ chal_type_name +'/' + chal_type_name + '-challenge-create.hbs', function(template_data){ var template = Handlebars.compile(template_data); $("#create-chal-entry-div").html(template({'nonce':nonce, 'script_root':script_root})); $.getScript(script_root + '/static/admin/js/templates/challenges/'+chal_type_name+'/'+chal_type_name+'-challenge-create.js', function(){ console.log('loaded'); }); }); } nonce = "{{ nonce }}"; $.get(script_root + '/admin/chal_types', function(data){ console.log(data); $("#create-chals-select").empty(); var chal_type_amt = Object.keys(data).length; if (chal_type_amt > 1){ var option = "<option> -- </option>"; $("#create-chals-select").append(option); for (var key in data){ var option = "<option value='{0}'>{1}</option>".format(key, data[key]); $("#create-chals-select").append(option); } } else if (chal_type_amt == 1)
}); $('#create-chals-select').change(function(){ var chal_type_name = $(this).find("option:selected").text(); load_chal_template(chal_type_name); });
{ var key = Object.keys(data)[0]; $("#create-chals-select").parent().parent().parent().empty(); load_chal_template(data[key]); }
conditional_block
chal-new.js
function load_chal_template(chal_type_name){ $.get(script_root + '/static/admin/js/templates/challenges/'+ chal_type_name +'/' + chal_type_name + '-challenge-create.hbs', function(template_data){ var template = Handlebars.compile(template_data); $("#create-chal-entry-div").html(template({'nonce':nonce, 'script_root':script_root})); $.getScript(script_root + '/static/admin/js/templates/challenges/'+chal_type_name+'/'+chal_type_name+'-challenge-create.js', function(){ console.log('loaded'); }); }); } nonce = "{{ nonce }}"; $.get(script_root + '/admin/chal_types', function(data){ console.log(data); $("#create-chals-select").empty(); var chal_type_amt = Object.keys(data).length; if (chal_type_amt > 1){ var option = "<option> -- </option>"; $("#create-chals-select").append(option); for (var key in data){
$("#create-chals-select").parent().parent().parent().empty(); load_chal_template(data[key]); } }); $('#create-chals-select').change(function(){ var chal_type_name = $(this).find("option:selected").text(); load_chal_template(chal_type_name); });
var option = "<option value='{0}'>{1}</option>".format(key, data[key]); $("#create-chals-select").append(option); } } else if (chal_type_amt == 1) { var key = Object.keys(data)[0];
random_line_split
config.rs
use crate::files; use crate::package; use std::path::PathBuf; use serde_json; use treeflection::{Node, NodeRunner, NodeToken}; #[derive(Clone, Serialize, Deserialize, Node)] pub struct Config { pub current_package: Option<String>, pub netplay_region: Option<String>, pub auto_save_replay: bool, pub verify_package_hashes: bool, pub fullscreen: bool,
} impl Config { fn get_path() -> PathBuf { let mut path = files::get_path(); path.push("config.json"); path } pub fn load() -> Config { if let Ok (json) = files::load_json(Config::get_path()) { if let Ok (mut config) = serde_json::from_value::<Config>(json) { // current_package may have been deleted since config was last saved if let Some (ref current_package) = config.current_package.clone() { if !package::exists(current_package.as_str()) { config.current_package = None; } } return config; } } warn!("{:?} is invalid or does not exist, loading default values", Config::get_path()); Config::default() } pub fn save(&self) { files::save_struct(Config::get_path(), self); } } impl Default for Config { fn default() -> Config { Config { current_package: None, netplay_region: None, auto_save_replay: false, verify_package_hashes: true, fullscreen: false, physical_device_name: None, } } }
pub physical_device_name: Option<String>,
random_line_split
config.rs
use crate::files; use crate::package; use std::path::PathBuf; use serde_json; use treeflection::{Node, NodeRunner, NodeToken}; #[derive(Clone, Serialize, Deserialize, Node)] pub struct Config { pub current_package: Option<String>, pub netplay_region: Option<String>, pub auto_save_replay: bool, pub verify_package_hashes: bool, pub fullscreen: bool, pub physical_device_name: Option<String>, } impl Config { fn get_path() -> PathBuf { let mut path = files::get_path(); path.push("config.json"); path } pub fn
() -> Config { if let Ok (json) = files::load_json(Config::get_path()) { if let Ok (mut config) = serde_json::from_value::<Config>(json) { // current_package may have been deleted since config was last saved if let Some (ref current_package) = config.current_package.clone() { if !package::exists(current_package.as_str()) { config.current_package = None; } } return config; } } warn!("{:?} is invalid or does not exist, loading default values", Config::get_path()); Config::default() } pub fn save(&self) { files::save_struct(Config::get_path(), self); } } impl Default for Config { fn default() -> Config { Config { current_package: None, netplay_region: None, auto_save_replay: false, verify_package_hashes: true, fullscreen: false, physical_device_name: None, } } }
load
identifier_name
config.rs
use crate::files; use crate::package; use std::path::PathBuf; use serde_json; use treeflection::{Node, NodeRunner, NodeToken}; #[derive(Clone, Serialize, Deserialize, Node)] pub struct Config { pub current_package: Option<String>, pub netplay_region: Option<String>, pub auto_save_replay: bool, pub verify_package_hashes: bool, pub fullscreen: bool, pub physical_device_name: Option<String>, } impl Config { fn get_path() -> PathBuf { let mut path = files::get_path(); path.push("config.json"); path } pub fn load() -> Config { if let Ok (json) = files::load_json(Config::get_path())
warn!("{:?} is invalid or does not exist, loading default values", Config::get_path()); Config::default() } pub fn save(&self) { files::save_struct(Config::get_path(), self); } } impl Default for Config { fn default() -> Config { Config { current_package: None, netplay_region: None, auto_save_replay: false, verify_package_hashes: true, fullscreen: false, physical_device_name: None, } } }
{ if let Ok (mut config) = serde_json::from_value::<Config>(json) { // current_package may have been deleted since config was last saved if let Some (ref current_package) = config.current_package.clone() { if !package::exists(current_package.as_str()) { config.current_package = None; } } return config; } }
conditional_block
core.js
var fs = require('fs'); // Core functions for loading and reloading modules module.exports = (function() { var core = { // Define core variables client: false, secrets: false, loaded: {}, modules: [], init: function(client, modules, secrets) { core.secrets = secrets; // Only set the client if it hasn't been initialized yet if(!core.client) core.client = client; // Get core modules var core_modules = require("./config/core.js"); // Loop through core modules for(var i = 0, l = core_modules.length; i < l; i++) { core.modules.push({type: 'core', name: core_modules[i]}); } // Loop through all non-essential modules for(var i = 0, l = modules.length; i < l; i++) { core.modules.push({type: 'modules', name: modules[i]}); } // Now loop through all modules and load them for(var i = 0, l = core.modules.length; i < l; i++) { core.load(core.modules[i]); } }, load: function(module) { var path = "./"+module.type+"/"+module.name+".js"; // Make sure the module exists! if(fs.existsSync(path)) { // Create a unique ID for the module based on it's type and name var module_id = module.type + "/" + module.name; var module; // Now require the module try { module = require(path); } catch(error) { console.log("Error: The module failed to require!", error); } core.loaded[module_id] = module; // And check if it has a load function if(typeof core.loaded[module_id].load == "function") { core.loaded[module_id].load(core.client, core); } else { console.log("Warning: Module '"+module.name+"' cannot be loaded!"); } } else { console.log("Warning: Module '"+module.name+"' does not exist!"); } }, unload: function(module) { var module_id = module.type + "/" + module.name; // Make sure this module is actually loaded if(typeof core.loaded[module_id] != "undefined") { // Does this module have an unload function? if(typeof core.loaded[module_id].unload == "function") { core.loaded[module_id].unload(core.client, core); } else { console.log("Warning: Module '"+module.name+"' cannot be unloaded!"); } delete core.loaded[module]; delete require.cache[require.resolve("./"+module.type+"/"+module.name+".js")]; } }, reload: function(module) { core.unload(module); core.load(module);
return { init: core.init, load: core.load, unload: core.unload, reload: core.reload }; })();
} };
random_line_split
core.js
var fs = require('fs'); // Core functions for loading and reloading modules module.exports = (function() { var core = { // Define core variables client: false, secrets: false, loaded: {}, modules: [], init: function(client, modules, secrets) { core.secrets = secrets; // Only set the client if it hasn't been initialized yet if(!core.client) core.client = client; // Get core modules var core_modules = require("./config/core.js"); // Loop through core modules for(var i = 0, l = core_modules.length; i < l; i++) { core.modules.push({type: 'core', name: core_modules[i]}); } // Loop through all non-essential modules for(var i = 0, l = modules.length; i < l; i++) { core.modules.push({type: 'modules', name: modules[i]}); } // Now loop through all modules and load them for(var i = 0, l = core.modules.length; i < l; i++)
}, load: function(module) { var path = "./"+module.type+"/"+module.name+".js"; // Make sure the module exists! if(fs.existsSync(path)) { // Create a unique ID for the module based on it's type and name var module_id = module.type + "/" + module.name; var module; // Now require the module try { module = require(path); } catch(error) { console.log("Error: The module failed to require!", error); } core.loaded[module_id] = module; // And check if it has a load function if(typeof core.loaded[module_id].load == "function") { core.loaded[module_id].load(core.client, core); } else { console.log("Warning: Module '"+module.name+"' cannot be loaded!"); } } else { console.log("Warning: Module '"+module.name+"' does not exist!"); } }, unload: function(module) { var module_id = module.type + "/" + module.name; // Make sure this module is actually loaded if(typeof core.loaded[module_id] != "undefined") { // Does this module have an unload function? if(typeof core.loaded[module_id].unload == "function") { core.loaded[module_id].unload(core.client, core); } else { console.log("Warning: Module '"+module.name+"' cannot be unloaded!"); } delete core.loaded[module]; delete require.cache[require.resolve("./"+module.type+"/"+module.name+".js")]; } }, reload: function(module) { core.unload(module); core.load(module); } }; return { init: core.init, load: core.load, unload: core.unload, reload: core.reload }; })();
{ core.load(core.modules[i]); }
conditional_block
index.js
const symbols = require('../symbols'); const createToken = require('../create-token'); const cleanToken = require('./clean'); let depthPointer = 0; const addTokenToExprTree = (ast, token) => { let level = ast; for (let i = 0; i < depthPointer; i++) { //set the level to the rightmost deepest branch level = level[level.length - 1]; } level.push(token); }; const popExpr = () => depthPointer--; const pushExpr = (ast) => { addTokenToExprTree(ast, []); depthPointer++; }; module.exports = (_tokens) => { // Reset depth pointer depthPointer = 0; const tokens = _tokens .map(t => Object.assign({}, t)) .map(cleanToken); let ast = []; for (let i = 0; i < tokens.length; i++) { const token = tokens[i]; if (token.type === symbols.LPAREN) { pushExpr(ast); continue;
addTokenToExprTree(ast, token); } return ast; };
} else if (token.type === symbols.RPAREN) { popExpr(); continue; }
random_line_split
index.js
const symbols = require('../symbols'); const createToken = require('../create-token'); const cleanToken = require('./clean'); let depthPointer = 0; const addTokenToExprTree = (ast, token) => { let level = ast; for (let i = 0; i < depthPointer; i++) { //set the level to the rightmost deepest branch level = level[level.length - 1]; } level.push(token); }; const popExpr = () => depthPointer--; const pushExpr = (ast) => { addTokenToExprTree(ast, []); depthPointer++; }; module.exports = (_tokens) => { // Reset depth pointer depthPointer = 0; const tokens = _tokens .map(t => Object.assign({}, t)) .map(cleanToken); let ast = []; for (let i = 0; i < tokens.length; i++)
return ast; };
{ const token = tokens[i]; if (token.type === symbols.LPAREN) { pushExpr(ast); continue; } else if (token.type === symbols.RPAREN) { popExpr(); continue; } addTokenToExprTree(ast, token); }
conditional_block