code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
""" Commands for X-ray Diffraction Note that an XRD camera must be installed! """ def setup_epics_shutter(prefix='13MARCCD4:'): """ Setup Epics shutter for CCD camera open /close pv = 13IDA:m70.VAL (SSA H WID) open val = 0.080, close val = -0.020 """ caput(prefix+'cam1:ShutterOpenEPICS.OUT', '13IDA:m70.VAL') caput(prefix+'cam1:ShutterCloseEPICS.OUT', '13IDA:m70.VAL') caput(prefix+'cam1:ShutterOpenEPICS.OCAL', '0.080') caput(prefix+'cam1:ShutterCloseEPICS.OCAL', '-0.020') caput(prefix+'cam1:ShutterOpenDelay', 1.50) caput(prefix+'cam1:ShutterCloseDelay', 0.0) caput(prefix+'cam1:ShutterMode', 1) #enddef def clear_epics_shutter(prefix='13MARCCD4:'): """ Clear Epics shutter PV for CCD camera """ caput(prefix+'cam1:ShutterOpenEPICS.OUT', '') caput(prefix+'cam1:ShutterCloseEPICS.OUT', '') caput(prefix+'cam1:ShutterOpenEPICS.OCAL', '0') caput(prefix+'cam1:ShutterCloseEPICS.OCAL', '0') caput(prefix+'cam1:ShutterOpenDelay', 0.1) caput(prefix+'cam1:ShutterCloseDelay', 0.1) caput(prefix+'cam1:ShutterMode', 0) #enddef def close_ccd_shutter(): caput('13IDA:m70.VAL', -0.025, wait=True) sleep(1.0) #enddef def open_ccd_shutter(): caput('13IDA:m70.VAL', 0.080, wait=True) sleep(1.0) #enddef def save_xrd(name, t=10, ext=None, prefix='13PEL1:', timeout=60.0): ## prefix='13PEL1:' prefix='13MARCCD1:' """ Save XRD image from XRD camera. Parameters: name (string): name of datafile t (float): exposure time in seconds [default= 10] ext (int or None): number for file extension if left as None, the extension will be auto-incremented. prefix (string): PV prefix for areaDetector camera ['13PE1:'] timeout (float): maximumn time in seconds to wait for image to be saved [60] Examples: save_xrd('CeO2', t=20) Note: calls one of `save_xrd_marccd` or `save_xrd_pe` See Also: `save_xrd_marccd`, `save_xrd_pe` """ if 'mar' in prefix.lower(): save_xrd_marccd(name, t=t, ext=ext, prefix=prefix) else: save_xrd_pe(name, t=t, ext=ext, prefix=prefix) #endif #enddef def save_xrd_pe(name, t=10, ext=None, prefix='13PEL1:', timeout=60.0): """ Save XRD image from Perkin-Elmer camera. Parameters: name (string): name of datafile t (float): exposure time in seconds [default= 10] ext (int or None): number for file extension if left as None, the extension will be auto-incremented. prefix (string): PV prefix for areaDetector camera ['13PE1:'] timeout (float): maximumn time in seconds to wait for image to be saved [60] Examples: save_xrd_pe('CeO2', t=20) Note: detector pool PE detector has prefix like 'dp_pe2:' """ # prefix='dp_pe2:' # save shutter mode, disable shutter for now shutter_mode = caget(prefix+'cam1:ShutterMode') caput(prefix+'cam1:ShutterMode', 0) sleep(0.1) caput(prefix+'cam1:Acquire', 0) sleep(0.1) print("Save XRD...") caput(prefix+'TIFF1:EnableCallbacks', 0) caput(prefix+'TIFF1:AutoSave', 0) caput(prefix+'TIFF1:AutoIncrement', 1) caput(prefix+'TIFF1:FileName', name) if ext is not None: caput(prefix+'TIFF1:FileNumber', ext) #endif caput(prefix+'TIFF1:EnableCallbacks', 1) caput(prefix+'cam1:ImageMode', 3) sleep(0.5) acq_time =caget(prefix+'cam1:AcquireTime') numimages = int(t*1.0/acq_time) caput(prefix+'cam1:NumImages', numimages) # expose caput(prefix+'cam1:Acquire', 1) sleep(0.5 + max(0.5, 0.5*t)) t0 = clock() nrequested = caget(prefix+'cam1:NumImages') print('Wait for Acquire ... %i' % nrequested) while ((1 == caget(prefix+'cam1:Acquire')) and (clock()-t0 < timeout)): sleep(0.25) #endwhile print('Acquire Done, writing file %s' % name) sleep(0.1) # clean up, returning to short dwell time caput(prefix+'TIFF1:WriteFile', 1) caput(prefix+'TIFF1:EnableCallbacks', 0) sleep(0.5) caput(prefix+'cam1:ImageMode', 2) caput(prefix+'cam1:ShutterMode', shutter_mode) sleep(0.5) caput(prefix+'cam1:Acquire', 1) sleep(1.5) #enddef def save_xrd_marccd(name, t=10, ext=None, prefix='13MARCCD4:', timeout=60.0): """ save XRD image from MARCCD (Rayonix 165) camera to file Parameters: name (string): name of datafile t (float): exposure time in seconds [default= 10] ext (int or None): number for file extension if left as None, the extension will be auto-incremented. prefix (string): PV prefix for areaDetector camera ['13MARCCD1:'] timeout (float): maximumn time in seconds to wait for image to be saved [60] Examples: save_xrd_marccd('CeO2', t=20) Note: The marccd requires the Epics Shutter to be set up correctly. """ start_time = systime() # save shutter mode, disable shutter for now shutter_mode = caget(prefix+'cam1:ShutterMode') # NOTE: Need to start acquisition with the shutter # having been closed for awhile # using the SSA H Width as shutter we want # NOTE: Need to start acquisition with the shutter # having been closed for awhile # using the SSA H Width as shutter we want caput(prefix+'cam1:ShutterControl', 0) close_ccd_shutter() caput(prefix+'cam1:FrameType', 0) caput(prefix+'cam1:ImageMode', 0) caput(prefix+'cam1:AutoSave', 1) caput(prefix+'cam1:AutoIncrement', 1) caput(prefix+'cam1:FileName', name) if ext is not None: caput(prefix+'cam1:FileNumber', ext) #endif caput(prefix+'cam1:AcquireTime', t) sleep(0.1) # expose caput(prefix+'cam1:Acquire', 1) sleep(1.0 + max(1.0, t)) t0 = systime() print('Wait for Acquire ... ') while ((1 == caget(prefix+'cam1:Acquire')) and (clock()-t0 < timeout)): sleep(0.25) #endwhile fname = caget(prefix+'cam1:FullFileName_RBV', as_string=True) print('Acquire Done! %.3f sec' % (systime()-start_time)) print('Wrote %s' % fname) sleep(1.0) caput(prefix+'cam1:ShutterControl', 1) #enddef def xrd_at(posname, t): move_samplestage(posname, wait=True) save_xrd(posname, t=t, ext=1) #enddef def xrd_bgr_marccd(prefix='13MARCCD4:', timeout=120.0): """ collect XRD Background for marccd Parameters: prefix (string): PV prefix for camera ['13MARCCD1:'] timeout (float): maximum time to wait [120] """ caput(prefix+'cam1:ShutterControl', 0) caput(prefix+'cam1:FrameType', 1) sleep(0.1) caput(prefix+'cam1:Acquire', 1) sleep(3) t0 = clock() print('Wait for Acquire ... ') while ((1 == caget(prefix+'cam1:Acquire')) and (clock()-t0 < timeout)): sleep(0.25) #endwhile sleep(2.0) #enddef def xrd_bgr(prefix='13PEL1:'): """ collect XRD Background for Perkin Elmer Parameters: prefix (string): PV prefix for camera ['13MARCCD1:'] """ caput(prefix+'cam1:ShutterMode', 1) immode = caget(prefix+'cam1:ImageMode') caput(prefix+'cam1:ImageMode', 1) caput(prefix+'cam1:ShutterControl', 0) sleep(3) caput(prefix+'cam1:PEAcquireOffset', 1) sleep(5) caput(prefix+'cam1:ShutterControl', 1) caput(prefix+'cam1:ImageMode', immode) caput(prefix+'cam1:Acquire', 1) sleep(2.0) #enddef
newville/microprobe_docs
doc/macros/xrd.py
Python
bsd-2-clause
7,656
<?php namespace PhpSsrs\ReportingService2010; class ListScheduledItemsResponse { /** * * @var CatalogItem[] $Items * @access public */ public $Items = null; /** * * @param CatalogItem[] $Items * @access public */ public function __construct($Items = null) { $this->Items = $Items; } }
chriskl/phpssrs
library/PhpSsrs/ReportingService2010/ListScheduledItemsResponse.php
PHP
bsd-2-clause
332
package demo.inpro.system.pento.nlu; import inpro.incremental.processor.RMRSComposer.Resolver; import inpro.irmrsc.rmrs.Formula; import inpro.irmrsc.rmrs.SimpleAssertion; import inpro.irmrsc.rmrs.SimpleAssertion.Type; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.JFrame; import javax.xml.bind.JAXBException; import work.inpro.gui.pentomino.january.GameCanvas; import work.inpro.system.pentomino.Column; import work.inpro.system.pentomino.Field; import work.inpro.system.pentomino.PentoObject; import work.inpro.system.pentomino.Piece; import work.inpro.system.pentomino.Row; import work.inpro.system.pentomino.Setting; import edu.cmu.sphinx.util.props.PropertyException; import edu.cmu.sphinx.util.props.PropertySheet; import edu.cmu.sphinx.util.props.S4Boolean; import edu.cmu.sphinx.util.props.S4String; public class PentoRMRSResolver implements Resolver { /** the pento setting to work with */ private Setting setting; /** config for creating setting from XML */ @S4String(defaultValue = "") public final static String PROP_SETTING_XML = "settingXML"; /** a list of lemmata to ignore when resolving */ private List<String> skipList = new ArrayList<String>(); /** a mapping of rmrs lemmata to pento attributes */ Map<String,String> mappedAttributeLemmata = new HashMap<String,String>(); /** a canvas to display current setting */ private GameCanvas gameCanvas; /** a frame for display the setting's canvas */ private static JFrame gameFrame = new JFrame("Pento Setting"); /** boolean for determining whether to show the setting */ @S4Boolean(defaultValue = true) public final static String PROP_SHOW_SETTING = "showSetting"; private boolean showSetting; private boolean updateSetting = true; // Change to suppress changes to the GUI @Override public void newProperties(PropertySheet ps) throws PropertyException { showSetting = ps.getBoolean(PROP_SHOW_SETTING); try { setting = Setting.createFromXML(new URL(ps.getString(PROP_SETTING_XML)).openStream()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (JAXBException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // FIXME: load this from somewhere else... skipList.add("def"); skipList.add("nehmen"); skipList.add("legen"); skipList.add("löschen"); skipList.add("drehen"); skipList.add("spiegeln"); skipList.add("addressee"); mappedAttributeLemmata.put("rot","red"); mappedAttributeLemmata.put("gelb","yellow"); mappedAttributeLemmata.put("grün","green"); mappedAttributeLemmata.put("blau","blue"); mappedAttributeLemmata.put("grau","gray"); mappedAttributeLemmata.put("kreuz","X"); mappedAttributeLemmata.put("gewehr","N"); mappedAttributeLemmata.put("schlange","Z"); mappedAttributeLemmata.put("treppe","W"); mappedAttributeLemmata.put("brücke","U"); mappedAttributeLemmata.put("handy","P"); mappedAttributeLemmata.put("krücke","Y"); mappedAttributeLemmata.put("balken","I"); mappedAttributeLemmata.put("winkel","V"); //mappedAttributeLemmata.put("ecke","V"); Grrrrr, piece and location have the same lemma mappedAttributeLemmata.put("mast","T"); mappedAttributeLemmata.put("pistole","F"); mappedAttributeLemmata.put("sieben","L"); // Build the gui if (showSetting) { this.updateCanvas(); this.drawScene(); } } public Setting getSetting() { return setting; } @SuppressWarnings("unchecked") @Override public Map<Integer, List<?>> resolvesObjects(Formula f) { Map<Integer, List<?>> matches = new HashMap<Integer, List<?>>(); List<SimpleAssertion> transitives = new ArrayList<SimpleAssertion>(); List<SimpleAssertion> ditransitives = new ArrayList<SimpleAssertion>(); // Sort assertions, since we want to do transitives before ditransitives // Also initialize a map for each predicate argument to all world objects (these lists will be reduced below) for (SimpleAssertion sa : f.getNominalAssertions()) { if (skipList.contains(sa.getPredicateName())) { continue; } else if (sa.getType() == Type.TRANSITIVE) { transitives.add(sa); matches.put(sa.getArguments().get(0), this.setting.getPentoObjects()); } else if (sa.getType() == Type.DITRANSITIVE) { ditransitives.add(sa); matches.put(sa.getArguments().get(0), this.setting.getPentoObjects()); matches.put(sa.getArguments().get(1), this.setting.getPentoObjects()); } } //logger.warn("New Formula - Trans: " + transitives.toString() + " Ditrans: " + ditransitives.toString()); // Reduce the number of objects that resolve for each transitive argument for (SimpleAssertion sa : transitives) { List<PentoObject> newMatches = new ArrayList<PentoObject>(); for (PentoObject po : (List<PentoObject>) matches.get(sa.getArguments().get(0))) { if (transitivePredicateResolvesObject(po, sa.getPredicateName())) { newMatches.add(po); } } matches.put(sa.getArguments().get(0), newMatches); } // Reduce the number of objects that resolve for each ditransitive argument for (SimpleAssertion dsa : ditransitives) { List<PentoObject> firstObjectMatches = new ArrayList<PentoObject>(); List<PentoObject> secondObjectMatches = new ArrayList<PentoObject>(); for (PentoObject firstObject : (List<PentoObject>) matches.get(dsa.getArguments().get(0)) ) { for (PentoObject secondObject : (List<PentoObject>) matches.get(dsa.getArguments().get(1)) ) { if (this.ditransitivePredicateResolvesObjects(firstObject, secondObject, dsa.getPredicateName())) { if (!firstObjectMatches.contains(firstObject)) firstObjectMatches.add(firstObject); if (!secondObjectMatches.contains(secondObject)) secondObjectMatches.add(secondObject); } } } matches.put(dsa.getArguments().get(0), firstObjectMatches); matches.put(dsa.getArguments().get(1), secondObjectMatches); } if (this.showSetting) { for (Integer id : matches.keySet()) { for (Piece piece : this.setting.getPieces()) { piece.setSelect(false); for (PentoObject po : (List<PentoObject>) matches.get(id)) { if (po instanceof Piece) { System.out.println(po); ((Piece) po).setSelect(true); } } } } if (this.updateSetting) this.updateCanvas(); } return matches; } @Override public int resolves(Formula f) { Map<Integer, List<?>> matches = this.resolvesObjects(f); if (matches.keySet().isEmpty()) { return 0; } boolean allUnique = true; boolean piecesUnique = true; for (Integer id : matches.keySet()) { if (matches.get(id).isEmpty()) { //logger.warn("Nothing resolved for predicate argument " + id); // else any empties? -> -1 return -1; } else if (matches.get(id).size() > 1) { allUnique = false; if (matches.get(id).get(0) instanceof Piece) { piecesUnique = false; } } } if (allUnique || piecesUnique) { // all uniques or only pieces are uniques -> 1 return 1; } else { return 0; } } @SuppressWarnings("unchecked") @Override public int resolvesObject(Formula f, String tileId) { int ret = -1; // nothing matched yet Map<Integer, List<?>> matches = this.resolvesObjects(f); for (Integer id : matches.keySet()) { for (PentoObject po : (List<PentoObject>) matches.get(id)) { if (po instanceof Piece && po.getID().equals(tileId)) { if (matches.get(id).size() == 1) { return 1; // one object was a match and it was in a singleton list } else if (matches.get(id).size() == 2) { // if two, then they have to be in two different grids. if (!((PentoObject) matches.get(id).get(0)).getField().getGrid().equals(((PentoObject) matches.get(id).get(1)).getField().getGrid())) { return 1; } else { ret = 0; } } else { ret = 0; // continue, but at least we had a match in a longer list } } } } return ret; } public void updateSetting(Setting newsetting) { setting = newsetting; drawScene(); } public void setPerformDomainAction(boolean performActions) { updateSetting = performActions; } /** * Method for checking if a PentoObject matches attributes. * @param po the PentoObject to check * @param predicate the attribute (lemmatized) * @return true if po matched attribute */ private boolean transitivePredicateResolvesObject(PentoObject po, String predicate) { boolean resolved = false; if (mappedAttributeLemmata.containsKey(predicate)) { if (po instanceof Piece) { resolved = (Character.toString(((Piece) po).getType()).equals(mappedAttributeLemmata.get(predicate)) || po.hasColor(mappedAttributeLemmata.get(predicate)) || po.hasLabel(predicate)); } else if (po instanceof Field) { resolved = (po.hasColor(mappedAttributeLemmata.get(predicate)) || po.hasLabel(predicate)); } } else if (predicate.equals("oben")) { resolved = po.isTop(); } else if (predicate.equals("unten")) { resolved = po.isBottom(); } else if (predicate.equals("links")) { resolved = po.isLeft(); } else if (predicate.equals("rechts")) { resolved = po.isRight(); } else if (predicate.equals("ecke")) { resolved = po.isCorner(); } else if (predicate.equals("mitte")) { resolved = po.isCentre(); } else if (predicate.equals("teil") || predicate.toLowerCase().equals("pper")) { // lower casing because robust ppers are PPERs resolved = po instanceof Piece; } else if (predicate.equals("feld")) { resolved = po instanceof Field; } else if (predicate.equals("erste")) { resolved = po.isFirst(); } else if (predicate.equals("zweite")) { resolved = po.isSecond(); } else if (predicate.equals("dritte")) { resolved = po.isThird(); } else if (predicate.equals("spalte")) { resolved = po instanceof Column; } else if (predicate.equals("zeile")) { resolved = po instanceof Row; } else if (predicate.equals("horizontal")) { resolved = false; } else if (predicate.equals("vertikal")) { resolved = false; } return resolved; } /** * Method for checking if two PentoObject resolve with a given predicate. * For instance, in(x,y) is true if x is in y and x is a piece and y a tile... * @param firstObject the first object * @param secondObject the second object * @param predicate the predicate to check the two objects with */ private boolean ditransitivePredicateResolvesObjects(PentoObject firstObject, PentoObject secondObject, String predicate) { boolean resolves = false; if (predicate.equals("in") || predicate.equals("aus")) { resolves = firstObject.isIn(secondObject); // Use this instead if you only want pieces to be in things, not fields // resolves = firstObject.isIn(secondObject) && // firstObject instanceof Piece && // !(secondObject instanceof Piece); } else if (predicate.equals("auf") || predicate.equals("über")) { resolves = firstObject.isAbove(secondObject) && firstObject instanceof Piece && secondObject instanceof Piece; } else if (predicate.equals("neben")) { resolves = firstObject.isNextTo(secondObject) && firstObject instanceof Piece && secondObject instanceof Piece; } else if (predicate.equals("unter")) { resolves = firstObject.isBelow(secondObject) && firstObject instanceof Piece && secondObject instanceof Piece; } return resolves; } /** must be called to update the gameCanvas to reflect the current setting */ private synchronized void updateCanvas() { gameCanvas = new GameCanvas(setting); gameCanvas.hideCursor(); gameCanvas.setVisible(true); gameFrame.setContentPane(gameCanvas); gameFrame.validate(); gameFrame.repaint(); } /** * Sets up the scene from local variable for setting XML. */ private void drawScene() { try { gameCanvas = new GameCanvas(setting); gameCanvas.hideCursor(); resetGUI(this.setting, "Pento Canvas", this.gameCanvas); } catch (Exception e) { e.printStackTrace(); } } /** * Resets GUI */ protected static void resetGUI(Setting setting, String frameName, GameCanvas c) { gameFrame.setName(frameName); gameFrame.setContentPane(c); gameFrame.pack(); gameFrame.setSize(setting.getGrids().get(0).getNumColumns()*115, setting.getGrids().get(0).getNumRows()*120); gameFrame.setVisible(true); } }
ONatalia/Masterarbeit
src/demo/inpro/system/pento/nlu/PentoRMRSResolver.java
Java
bsd-2-clause
12,477
package org.fxmisc.richtext.demo; import java.util.Collection; import java.util.Collections; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.fxmisc.flowless.VirtualizedScrollPane; import org.fxmisc.richtext.CodeArea; import org.fxmisc.richtext.LineNumberFactory; import org.fxmisc.richtext.model.StyleSpans; import org.fxmisc.richtext.model.StyleSpansBuilder; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class XMLEditor extends Application { private static final Pattern XML_TAG = Pattern.compile("(?<ELEMENT>(</?\\h*)(\\w+)([^<>]*)(\\h*/?>))" +"|(?<COMMENT><!--[^<>]+-->)"); private static final Pattern ATTRIBUTES = Pattern.compile("(\\w+\\h*)(=)(\\h*\"[^\"]+\")"); private static final int GROUP_OPEN_BRACKET = 2; private static final int GROUP_ELEMENT_NAME = 3; private static final int GROUP_ATTRIBUTES_SECTION = 4; private static final int GROUP_CLOSE_BRACKET = 5; private static final int GROUP_ATTRIBUTE_NAME = 1; private static final int GROUP_EQUAL_SYMBOL = 2; private static final int GROUP_ATTRIBUTE_VALUE = 3; private static final String sampleCode = String.join("\n", new String[] { "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>", "<!-- Sample XML -->", "< orders >", " <Order number=\"1\" table=\"center\">", " <items>", " <Item>", " <type>ESPRESSO</type>", " <shots>2</shots>", " <iced>false</iced>", " <orderNumber>1</orderNumber>", " </Item>", " <Item>", " <type>CAPPUCCINO</type>", " <shots>1</shots>", " <iced>false</iced>", " <orderNumber>1</orderNumber>", " </Item>", " <Item>", " <type>LATTE</type>", " <shots>2</shots>", " <iced>false</iced>", " <orderNumber>1</orderNumber>", " </Item>", " <Item>", " <type>MOCHA</type>", " <shots>3</shots>", " <iced>true</iced>", " <orderNumber>1</orderNumber>", " </Item>", " </items>", " </Order>", "</orders>" }); public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { CodeArea codeArea = new CodeArea(); codeArea.setParagraphGraphicFactory(LineNumberFactory.get(codeArea)); codeArea.textProperty().addListener((obs, oldText, newText) -> { codeArea.setStyleSpans(0, computeHighlighting(newText)); }); codeArea.replaceText(0, 0, sampleCode); Scene scene = new Scene(new StackPane(new VirtualizedScrollPane<>(codeArea)), 600, 400); scene.getStylesheets().add(JavaKeywordsAsync.class.getResource("xml-highlighting.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.setTitle("XML Editor Demo"); primaryStage.show(); } private static StyleSpans<Collection<String>> computeHighlighting(String text) { Matcher matcher = XML_TAG.matcher(text); int lastKwEnd = 0; StyleSpansBuilder<Collection<String>> spansBuilder = new StyleSpansBuilder<>(); while(matcher.find()) { spansBuilder.add(Collections.emptyList(), matcher.start() - lastKwEnd); if(matcher.group("COMMENT") != null) { spansBuilder.add(Collections.singleton("comment"), matcher.end() - matcher.start()); } else { if(matcher.group("ELEMENT") != null) { String attributesText = matcher.group(GROUP_ATTRIBUTES_SECTION); spansBuilder.add(Collections.singleton("tagmark"), matcher.end(GROUP_OPEN_BRACKET) - matcher.start(GROUP_OPEN_BRACKET)); spansBuilder.add(Collections.singleton("anytag"), matcher.end(GROUP_ELEMENT_NAME) - matcher.end(GROUP_OPEN_BRACKET)); if(!attributesText.isEmpty()) { lastKwEnd = 0; Matcher amatcher = ATTRIBUTES.matcher(attributesText); while(amatcher.find()) { spansBuilder.add(Collections.emptyList(), amatcher.start() - lastKwEnd); spansBuilder.add(Collections.singleton("attribute"), amatcher.end(GROUP_ATTRIBUTE_NAME) - amatcher.start(GROUP_ATTRIBUTE_NAME)); spansBuilder.add(Collections.singleton("tagmark"), amatcher.end(GROUP_EQUAL_SYMBOL) - amatcher.end(GROUP_ATTRIBUTE_NAME)); spansBuilder.add(Collections.singleton("avalue"), amatcher.end(GROUP_ATTRIBUTE_VALUE) - amatcher.end(GROUP_EQUAL_SYMBOL)); lastKwEnd = amatcher.end(); } if(attributesText.length() > lastKwEnd) spansBuilder.add(Collections.emptyList(), attributesText.length() - lastKwEnd); } lastKwEnd = matcher.end(GROUP_ATTRIBUTES_SECTION); spansBuilder.add(Collections.singleton("tagmark"), matcher.end(GROUP_CLOSE_BRACKET) - lastKwEnd); } } lastKwEnd = matcher.end(); } spansBuilder.add(Collections.emptyList(), text.length() - lastKwEnd); return spansBuilder.create(); } }
cemartins/RichTextFX
richtextfx-demos/src/main/java/org/fxmisc/richtext/demo/XMLEditor.java
Java
bsd-2-clause
5,270
using UnityEngine; using System.Collections; namespace EA4S.Scanner { public class ScannerScrollBelt : MonoBehaviour { const float BELT_FACTOR = -0.4f; private Renderer rend; void Start() { rend = GetComponent<Renderer>(); } void Update() { float offset = Time.time * BELT_FACTOR * ScannerConfiguration.Instance.beltSpeed; rend.material.SetTextureOffset("_MainTex", new Vector2(offset, 0)); } } }
Norad-Eduapp4syria/Norad-Eduapp4syria
finalApprovedVersion/Antura/EA4S_Antura_U3D/Assets/_games/Scanner/_scripts/ScannerScrollBelt.cs
C#
bsd-2-clause
429
// Copyright (c) 2012, Susumu Yata // 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. // // 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 HOLDER 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. #include <iostream> #include <madoka/exception.h> #include <madoka/header.h> int main() try { madoka::Header header; header.set_width(1ULL << 30); header.set_depth(3); header.set_max_value((1ULL << 28) - 1); header.set_value_size(28); header.set_seed(123456789); header.set_table_size(1ULL << 32); header.set_file_size((1ULL << 32) + sizeof(madoka::Header)); MADOKA_THROW_IF(header.width() != (1ULL << 30)); MADOKA_THROW_IF(header.width_mask() != ((1ULL << 30) - 1)); MADOKA_THROW_IF(header.depth() != (3)); MADOKA_THROW_IF(header.max_value() != ((1ULL << 28) - 1)); MADOKA_THROW_IF(header.value_size() != 28); MADOKA_THROW_IF(header.seed() != 123456789); MADOKA_THROW_IF(header.table_size() != (1ULL << 32)); MADOKA_THROW_IF(header.file_size() != ((1ULL << 32) + sizeof(madoka::Header))); header.set_width(123456789); MADOKA_THROW_IF(header.width() != 123456789); MADOKA_THROW_IF(header.width_mask() != 0); return 0; } catch (const madoka::Exception &ex) { std::cerr << "error: " << ex.what() << std::endl; return 1; }
s-yata/madoka
test/header-test.cc
C++
bsd-2-clause
2,453
package storage import ( "fmt" "io" "path" "github.com/goamz/goamz/aws" "github.com/goamz/goamz/s3" ) /* Repository data is stored in Amazon S3. Valid Params for KST_S3: * "awsregion" The code for the AWS Region, for example "us-east-1" * "bucket" The name of the AWS bucket * "prefix" An optional prefix for the bucket contents, for example "pulldeploy" */ const KST_S3 AccessMethod = "s3" // stS3 is used for PullDeploy repositories in Amazon S3. type stS3 struct { regionName string // Name of the AWS Region with our bucket bucketName string // Name of the S3 bucket pathPrefix string // Optional prefix to namespace our bucket bucket *s3.Bucket // Handle to the S3 bucket } // Initialize the repository object. func (st *stS3) init(params Params) error { // Extract the AWS region name. if regionName, ok := params["awsregion"]; ok { st.regionName = regionName } // Extract the AWS bucket name. if bucketName, ok := params["bucket"]; ok { st.bucketName = bucketName } // Extract the optional prefix for our paths. if pathPrefix, ok := params["prefix"]; ok { st.pathPrefix = pathPrefix } // Validate the region. region, ok := aws.Regions[st.regionName] if !ok { validSet := "" for k := range aws.Regions { validSet += " " + k } return fmt.Errorf("Invalid AWS region name: '%s' Valid values:%s", st.regionName, validSet) } // Pull AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY out of the environment. auth, err := aws.EnvAuth() if err != nil { return err } // Open a handle to the bucket. s := s3.New(auth, region) st.bucket = s.Bucket(st.bucketName) return nil } // Get fetches the contents of a repository file into a byte array. func (st *stS3) Get(repoPath string) ([]byte, error) { return st.bucket.Get(st.makeS3Path(repoPath)) } // Put writes the contents of a byte array into a repository file. func (st *stS3) Put(repoPath string, data []byte) error { options := s3.Options{} return st.bucket.Put( st.makeS3Path(repoPath), data, "application/octet-stream", "authenticated-read", options, ) } // GetReader returns a stream handle for reading a repository file. func (st *stS3) GetReader(repoPath string) (io.ReadCloser, error) { return st.bucket.GetReader(st.makeS3Path(repoPath)) } // PutReader writes a stream to a repository file. func (st *stS3) PutReader(repoPath string, rc io.ReadCloser, length int64) error { options := s3.Options{} return st.bucket.PutReader( st.makeS3Path(repoPath), rc, length, "application/octet-stream", "authenticated-read", options, ) } // Delete removes a repository file. func (st *stS3) Delete(repoPath string) error { return st.bucket.Del(st.makeS3Path(repoPath)) } // Utility helper to generate a full S3 repository path. func (st *stS3) makeS3Path(repoPath string) string { if st.pathPrefix == "" { return repoPath } return path.Join(st.pathPrefix, repoPath) }
mredivo/pulldeploy
storage/s3.go
GO
bsd-2-clause
2,946
/*- * #%L * High-level BoneJ2 commands. * %% * Copyright (C) 2015 - 2020 Michael Doube, BoneJ developers * %% * 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. * * 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 HOLDERS 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. * #L% */ /* BSD 2-Clause License Copyright (c) 2018, Michael Doube, Richard Domander, Alessandro Felder All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. 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 HOLDER 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. */ package org.bonej.wrapperPlugins.wrapperUtils; import ij.ImagePlus; import java.util.Optional; import java.util.stream.Stream; import net.imagej.axis.Axes; import net.imagej.axis.AxisType; import net.imagej.axis.CalibratedAxis; import net.imagej.axis.TypedAxis; import net.imagej.space.AnnotatedSpace; import net.imagej.units.UnitService; import org.bonej.utilities.AxisUtils; import org.scijava.util.StringUtils; /** * Static utility methods that help display results to the user * * @author Richard Domander */ public final class ResultUtils { private ResultUtils() {} /** * Returns the exponent character of the elements in this space, e.g. '³' for * a spatial 3D space. * * @param space an N-dimensional space. * @param <S> type of the space. * @param <A> type of the axes. * @return the exponent character if the space has 2 - 9 spatial dimensions. * An empty character otherwise. */ public static <S extends AnnotatedSpace<A>, A extends TypedAxis> char getExponent(final S space) { final long dimensions = AxisUtils.countSpatialDimensions(space); if (dimensions == 2) { return '\u00B2'; } if (dimensions == 3) { return '\u00B3'; } if (dimensions == 4) { return '\u2074'; } if (dimensions == 5) { return '\u2075'; } if (dimensions == 6) { return '\u2076'; } if (dimensions == 7) { return '\u2077'; } if (dimensions == 8) { return '\u2078'; } if (dimensions == 9) { return '\u2079'; } // Return an "empty" character return '\u0000'; } /** * Returns a verbal description of the size of the elements in the given * space, e.g. "A" for 2D images and "V" for 3D images. * * @param space an N-dimensional space. * @param <S> type of the space. * @param <A> type of the axes. * @return the noun for the size of the elements. */ public static <S extends AnnotatedSpace<A>, A extends TypedAxis> String getSizeDescription(final S space) { final long dimensions = AxisUtils.countSpatialDimensions(space); if (dimensions == 2) { return "A"; } if (dimensions == 3) { return "V"; } return "Size"; } /** * Returns the common unit string, e.g. "mm<sup>3</sup>" that describes the * elements in the space. * <p> * The common unit is the unit of the first spatial axis if it can be * converted to the units of the other axes. * </p> * * @param space an N-dimensional space. * @param <S> type of the space. * @param unitService an {@link UnitService} to convert axis calibrations. * @param exponent an exponent to be added to the unit, e.g. '³'. * @return the unit string with the exponent. */ public static <S extends AnnotatedSpace<CalibratedAxis>> String getUnitHeader( final S space, final UnitService unitService, final String exponent) { final Optional<String> unit = AxisUtils.getSpatialUnit(space, unitService); if (!unit.isPresent()) { return ""; } final String unitHeader = unit.get(); if (unitHeader.isEmpty()) { // Don't show default units return ""; } return "(" + unitHeader + exponent + ")"; } /** * Gets the unit of the image calibration, which can be displayed to the user. * * @param imagePlus a ImageJ1 style {@link ImagePlus}. * @return calibration unit, or empty string if there's no unit. */ public static String getUnitHeader(final ImagePlus imagePlus) { final String unit = imagePlus.getCalibration().getUnit(); if (StringUtils.isNullOrEmpty(unit)) { return ""; } return "(" + unit + ")"; } /** * If needed, converts the given index to the ImageJ1 convention where Z, * Channel and Time axes start from 1. * * @param type type of the axis's dimension. * @param index the index in the axis. * @return index + 1 if type is Z, Channel or Time. Index otherwise. */ public static long toConventionalIndex(final AxisType type, final long index) { final Stream<AxisType> oneAxes = Stream.of(Axes.Z, Axes.CHANNEL, Axes.TIME); if (oneAxes.anyMatch(t -> t.equals(type))) { return index + 1; } return index; } }
bonej-org/BoneJ2
Modern/wrapperPlugins/src/main/java/org/bonej/wrapperPlugins/wrapperUtils/ResultUtils.java
Java
bsd-2-clause
6,867
//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the ASTContext interface. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTContext.h" #include "CXXABI.h" #include "Interp/Context.h" #include "clang/AST/APValue.h" #include "clang/AST/ASTConcept.h" #include "clang/AST/ASTMutationListener.h" #include "clang/AST/ASTTypeTraits.h" #include "clang/AST/Attr.h" #include "clang/AST/AttrIterator.h" #include "clang/AST/CharUnits.h" #include "clang/AST/Comment.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclBase.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclContextInternals.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclOpenMP.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/Mangle.h" #include "clang/AST/MangleNumberingContext.h" #include "clang/AST/NestedNameSpecifier.h" #include "clang/AST/RawCommentList.h" #include "clang/AST/RecordLayout.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/AST/Stmt.h" #include "clang/AST/TemplateBase.h" #include "clang/AST/TemplateName.h" #include "clang/AST/Type.h" #include "clang/AST/TypeLoc.h" #include "clang/AST/UnresolvedSet.h" #include "clang/AST/VTableBuilder.h" #include "clang/Basic/AddressSpaces.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/CommentOptions.h" #include "clang/Basic/ExceptionSpecificationType.h" #include "clang/Basic/FixedPoint.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/Linkage.h" #include "clang/Basic/ObjCRuntime.h" #include "clang/Basic/SanitizerBlacklist.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TargetCXXABI.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/XRayLists.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/PointerUnion.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Triple.h" #include "llvm/Support/Capacity.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cassert> #include <cstddef> #include <cstdint> #include <cstdlib> #include <map> #include <memory> #include <string> #include <tuple> #include <utility> using namespace clang; enum FloatingRank { Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank }; const Expr *ASTContext::traverseIgnored(const Expr *E) const { return traverseIgnored(const_cast<Expr *>(E)); } Expr *ASTContext::traverseIgnored(Expr *E) const { if (!E) return nullptr; switch (Traversal) { case ast_type_traits::TK_AsIs: return E; case ast_type_traits::TK_IgnoreImplicitCastsAndParentheses: return E->IgnoreParenImpCasts(); case ast_type_traits::TK_IgnoreUnlessSpelledInSource: return E->IgnoreUnlessSpelledInSource(); } llvm_unreachable("Invalid Traversal type!"); } ast_type_traits::DynTypedNode ASTContext::traverseIgnored(const ast_type_traits::DynTypedNode &N) const { if (const auto *E = N.get<Expr>()) { return ast_type_traits::DynTypedNode::create(*traverseIgnored(E)); } return N; } /// \returns location that is relevant when searching for Doc comments related /// to \p D. static SourceLocation getDeclLocForCommentSearch(const Decl *D, SourceManager &SourceMgr) { assert(D); // User can not attach documentation to implicit declarations. if (D->isImplicit()) return {}; // User can not attach documentation to implicit instantiations. if (const auto *FD = dyn_cast<FunctionDecl>(D)) { if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) return {}; } if (const auto *VD = dyn_cast<VarDecl>(D)) { if (VD->isStaticDataMember() && VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) return {}; } if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) { if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) return {}; } if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) { TemplateSpecializationKind TSK = CTSD->getSpecializationKind(); if (TSK == TSK_ImplicitInstantiation || TSK == TSK_Undeclared) return {}; } if (const auto *ED = dyn_cast<EnumDecl>(D)) { if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) return {}; } if (const auto *TD = dyn_cast<TagDecl>(D)) { // When tag declaration (but not definition!) is part of the // decl-specifier-seq of some other declaration, it doesn't get comment if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition()) return {}; } // TODO: handle comments for function parameters properly. if (isa<ParmVarDecl>(D)) return {}; // TODO: we could look up template parameter documentation in the template // documentation. if (isa<TemplateTypeParmDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTemplateParmDecl>(D)) return {}; // Find declaration location. // For Objective-C declarations we generally don't expect to have multiple // declarators, thus use declaration starting location as the "declaration // location". // For all other declarations multiple declarators are used quite frequently, // so we use the location of the identifier as the "declaration location". if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) || isa<ObjCPropertyDecl>(D) || isa<RedeclarableTemplateDecl>(D) || isa<ClassTemplateSpecializationDecl>(D) || // Allow association with Y across {} in `typedef struct X {} Y`. isa<TypedefDecl>(D)) return D->getBeginLoc(); else { const SourceLocation DeclLoc = D->getLocation(); if (DeclLoc.isMacroID()) { if (isa<TypedefDecl>(D)) { // If location of the typedef name is in a macro, it is because being // declared via a macro. Try using declaration's starting location as // the "declaration location". return D->getBeginLoc(); } else if (const auto *TD = dyn_cast<TagDecl>(D)) { // If location of the tag decl is inside a macro, but the spelling of // the tag name comes from a macro argument, it looks like a special // macro like NS_ENUM is being used to define the tag decl. In that // case, adjust the source location to the expansion loc so that we can // attach the comment to the tag decl. if (SourceMgr.isMacroArgExpansion(DeclLoc) && TD->isCompleteDefinition()) return SourceMgr.getExpansionLoc(DeclLoc); } } return DeclLoc; } return {}; } RawComment *ASTContext::getRawCommentForDeclNoCacheImpl( const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map<unsigned, RawComment *> &CommentsInTheFile) const { // If the declaration doesn't map directly to a location in a file, we // can't find the comment. if (RepresentativeLocForDecl.isInvalid() || !RepresentativeLocForDecl.isFileID()) return nullptr; // If there are no comments anywhere, we won't find anything. if (CommentsInTheFile.empty()) return nullptr; // Decompose the location for the declaration and find the beginning of the // file buffer. const std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(RepresentativeLocForDecl); // Slow path. auto OffsetCommentBehindDecl = CommentsInTheFile.lower_bound(DeclLocDecomp.second); // First check whether we have a trailing comment. if (OffsetCommentBehindDecl != CommentsInTheFile.end()) { RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second; if ((CommentBehindDecl->isDocumentation() || LangOpts.CommentOpts.ParseAllComments) && CommentBehindDecl->isTrailingComment() && (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) || isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) { // Check that Doxygen trailing comment comes after the declaration, starts // on the same line and in the same file as the declaration. if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) == Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first, OffsetCommentBehindDecl->first)) { return CommentBehindDecl; } } } // The comment just after the declaration was not a trailing comment. // Let's look at the previous comment. if (OffsetCommentBehindDecl == CommentsInTheFile.begin()) return nullptr; auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl; RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second; // Check that we actually have a non-member Doxygen comment. if (!(CommentBeforeDecl->isDocumentation() || LangOpts.CommentOpts.ParseAllComments) || CommentBeforeDecl->isTrailingComment()) return nullptr; // Decompose the end of the comment. const unsigned CommentEndOffset = Comments.getCommentEndOffset(CommentBeforeDecl); // Get the corresponding buffer. bool Invalid = false; const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, &Invalid).data(); if (Invalid) return nullptr; // Extract text between the comment and declaration. StringRef Text(Buffer + CommentEndOffset, DeclLocDecomp.second - CommentEndOffset); // There should be no other declarations or preprocessor directives between // comment and declaration. if (Text.find_first_of(";{}#@") != StringRef::npos) return nullptr; return CommentBeforeDecl; } RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); // If the declaration doesn't map directly to a location in a file, we // can't find the comment. if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) return nullptr; if (ExternalSource && !CommentsLoaded) { ExternalSource->ReadComments(); CommentsLoaded = true; } if (Comments.empty()) return nullptr; const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first; const auto CommentsInThisFile = Comments.getCommentsInFile(File); if (!CommentsInThisFile || CommentsInThisFile->empty()) return nullptr; return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile); } /// If we have a 'templated' declaration for a template, adjust 'D' to /// refer to the actual template. /// If we have an implicit instantiation, adjust 'D' to refer to template. static const Decl &adjustDeclToTemplate(const Decl &D) { if (const auto *FD = dyn_cast<FunctionDecl>(&D)) { // Is this function declaration part of a function template? if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) return *FTD; // Nothing to do if function is not an implicit instantiation. if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) return D; // Function is an implicit instantiation of a function template? if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate()) return *FTD; // Function is instantiated from a member definition of a class template? if (const FunctionDecl *MemberDecl = FD->getInstantiatedFromMemberFunction()) return *MemberDecl; return D; } if (const auto *VD = dyn_cast<VarDecl>(&D)) { // Static data member is instantiated from a member definition of a class // template? if (VD->isStaticDataMember()) if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember()) return *MemberDecl; return D; } if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) { // Is this class declaration part of a class template? if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate()) return *CTD; // Class is an implicit instantiation of a class template or partial // specialization? if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) { if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation) return D; llvm::PointerUnion<ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl *> PU = CTSD->getSpecializedTemplateOrPartial(); return PU.is<ClassTemplateDecl *>() ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>()) : *static_cast<const Decl *>( PU.get<ClassTemplatePartialSpecializationDecl *>()); } // Class is instantiated from a member definition of a class template? if (const MemberSpecializationInfo *Info = CRD->getMemberSpecializationInfo()) return *Info->getInstantiatedFrom(); return D; } if (const auto *ED = dyn_cast<EnumDecl>(&D)) { // Enum is instantiated from a member definition of a class template? if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum()) return *MemberDecl; return D; } // FIXME: Adjust alias templates? return D; } const RawComment *ASTContext::getRawCommentForAnyRedecl( const Decl *D, const Decl **OriginalDecl) const { if (!D) { if (OriginalDecl) OriginalDecl = nullptr; return nullptr; } D = &adjustDeclToTemplate(*D); // Any comment directly attached to D? { auto DeclComment = DeclRawComments.find(D); if (DeclComment != DeclRawComments.end()) { if (OriginalDecl) *OriginalDecl = D; return DeclComment->second; } } // Any comment attached to any redeclaration of D? const Decl *CanonicalD = D->getCanonicalDecl(); if (!CanonicalD) return nullptr; { auto RedeclComment = RedeclChainComments.find(CanonicalD); if (RedeclComment != RedeclChainComments.end()) { if (OriginalDecl) *OriginalDecl = RedeclComment->second; auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second); assert(CommentAtRedecl != DeclRawComments.end() && "This decl is supposed to have comment attached."); return CommentAtRedecl->second; } } // Any redeclarations of D that we haven't checked for comments yet? // We can't use DenseMap::iterator directly since it'd get invalid. auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * { auto LookupRes = CommentlessRedeclChains.find(CanonicalD); if (LookupRes != CommentlessRedeclChains.end()) return LookupRes->second; return nullptr; }(); for (const auto Redecl : D->redecls()) { assert(Redecl); // Skip all redeclarations that have been checked previously. if (LastCheckedRedecl) { if (LastCheckedRedecl == Redecl) { LastCheckedRedecl = nullptr; } continue; } const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl); if (RedeclComment) { cacheRawCommentForDecl(*Redecl, *RedeclComment); if (OriginalDecl) *OriginalDecl = Redecl; return RedeclComment; } CommentlessRedeclChains[CanonicalD] = Redecl; } if (OriginalDecl) *OriginalDecl = nullptr; return nullptr; } void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD, const RawComment &Comment) const { assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments); DeclRawComments.try_emplace(&OriginalD, &Comment); const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl(); RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD); CommentlessRedeclChains.erase(CanonicalDecl); } static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl<const NamedDecl *> &Redeclared) { const DeclContext *DC = ObjCMethod->getDeclContext(); if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) { const ObjCInterfaceDecl *ID = IMD->getClassInterface(); if (!ID) return; // Add redeclared method here. for (const auto *Ext : ID->known_extensions()) { if (ObjCMethodDecl *RedeclaredMethod = Ext->getMethod(ObjCMethod->getSelector(), ObjCMethod->isInstanceMethod())) Redeclared.push_back(RedeclaredMethod); } } } void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls, const Preprocessor *PP) { if (Comments.empty() || Decls.empty()) return; // See if there are any new comments that are not attached to a decl. // The location doesn't have to be precise - we care only about the file. const FileID File = SourceMgr.getDecomposedLoc((*Decls.begin())->getLocation()).first; auto CommentsInThisFile = Comments.getCommentsInFile(File); if (!CommentsInThisFile || CommentsInThisFile->empty() || CommentsInThisFile->rbegin()->second->isAttached()) return; // There is at least one comment not attached to a decl. // Maybe it should be attached to one of Decls? // // Note that this way we pick up not only comments that precede the // declaration, but also comments that *follow* the declaration -- thanks to // the lookahead in the lexer: we've consumed the semicolon and looked // ahead through comments. for (const Decl *D : Decls) { assert(D); if (D->isInvalidDecl()) continue; D = &adjustDeclToTemplate(*D); const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) continue; if (DeclRawComments.count(D) > 0) continue; if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) { cacheRawCommentForDecl(*D, *DocComment); comments::FullComment *FC = DocComment->parse(*this, PP, D); ParsedComments[D->getCanonicalDecl()] = FC; } } } comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC, const Decl *D) const { auto *ThisDeclInfo = new (*this) comments::DeclInfo; ThisDeclInfo->CommentDecl = D; ThisDeclInfo->IsFilled = false; ThisDeclInfo->fill(); ThisDeclInfo->CommentDecl = FC->getDecl(); if (!ThisDeclInfo->TemplateParameters) ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters; comments::FullComment *CFC = new (*this) comments::FullComment(FC->getBlocks(), ThisDeclInfo); return CFC; } comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const { const RawComment *RC = getRawCommentForDeclNoCache(D); return RC ? RC->parse(*this, nullptr, D) : nullptr; } comments::FullComment *ASTContext::getCommentForDecl( const Decl *D, const Preprocessor *PP) const { if (!D || D->isInvalidDecl()) return nullptr; D = &adjustDeclToTemplate(*D); const Decl *Canonical = D->getCanonicalDecl(); llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = ParsedComments.find(Canonical); if (Pos != ParsedComments.end()) { if (Canonical != D) { comments::FullComment *FC = Pos->second; comments::FullComment *CFC = cloneFullComment(FC, D); return CFC; } return Pos->second; } const Decl *OriginalDecl = nullptr; const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); if (!RC) { if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { SmallVector<const NamedDecl*, 8> Overridden; const auto *OMD = dyn_cast<ObjCMethodDecl>(D); if (OMD && OMD->isPropertyAccessor()) if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) return cloneFullComment(FC, D); if (OMD) addRedeclaredMethods(OMD, Overridden); getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden); for (unsigned i = 0, e = Overridden.size(); i < e; i++) if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) return cloneFullComment(FC, D); } else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { // Attach any tag type's documentation to its typedef if latter // does not have one of its own. QualType QT = TD->getUnderlyingType(); if (const auto *TT = QT->getAs<TagType>()) if (const Decl *TD = TT->getDecl()) if (comments::FullComment *FC = getCommentForDecl(TD, PP)) return cloneFullComment(FC, D); } else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) { while (IC->getSuperClass()) { IC = IC->getSuperClass(); if (comments::FullComment *FC = getCommentForDecl(IC, PP)) return cloneFullComment(FC, D); } } else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) { if (const ObjCInterfaceDecl *IC = CD->getClassInterface()) if (comments::FullComment *FC = getCommentForDecl(IC, PP)) return cloneFullComment(FC, D); } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { if (!(RD = RD->getDefinition())) return nullptr; // Check non-virtual bases. for (const auto &I : RD->bases()) { if (I.isVirtual() || (I.getAccessSpecifier() != AS_public)) continue; QualType Ty = I.getType(); if (Ty.isNull()) continue; if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { if (!(NonVirtualBase= NonVirtualBase->getDefinition())) continue; if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) return cloneFullComment(FC, D); } } // Check virtual bases. for (const auto &I : RD->vbases()) { if (I.getAccessSpecifier() != AS_public) continue; QualType Ty = I.getType(); if (Ty.isNull()) continue; if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) { if (!(VirtualBase= VirtualBase->getDefinition())) continue; if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP)) return cloneFullComment(FC, D); } } } return nullptr; } // If the RawComment was attached to other redeclaration of this Decl, we // should parse the comment in context of that other Decl. This is important // because comments can contain references to parameter names which can be // different across redeclarations. if (D != OriginalDecl && OriginalDecl) return getCommentForDecl(OriginalDecl, PP); comments::FullComment *FC = RC->parse(*this, PP, D); ParsedComments[Canonical] = FC; return FC; } void ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C, TemplateTemplateParmDecl *Parm) { ID.AddInteger(Parm->getDepth()); ID.AddInteger(Parm->getPosition()); ID.AddBoolean(Parm->isParameterPack()); TemplateParameterList *Params = Parm->getTemplateParameters(); ID.AddInteger(Params->size()); for (TemplateParameterList::const_iterator P = Params->begin(), PEnd = Params->end(); P != PEnd; ++P) { if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { ID.AddInteger(0); ID.AddBoolean(TTP->isParameterPack()); const TypeConstraint *TC = TTP->getTypeConstraint(); ID.AddBoolean(TC != nullptr); if (TC) TC->getImmediatelyDeclaredConstraint()->Profile(ID, C, /*Canonical=*/true); if (TTP->isExpandedParameterPack()) { ID.AddBoolean(true); ID.AddInteger(TTP->getNumExpansionParameters()); } else ID.AddBoolean(false); continue; } if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { ID.AddInteger(1); ID.AddBoolean(NTTP->isParameterPack()); ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); if (NTTP->isExpandedParameterPack()) { ID.AddBoolean(true); ID.AddInteger(NTTP->getNumExpansionTypes()); for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { QualType T = NTTP->getExpansionType(I); ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); } } else ID.AddBoolean(false); continue; } auto *TTP = cast<TemplateTemplateParmDecl>(*P); ID.AddInteger(2); Profile(ID, C, TTP); } Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause(); ID.AddBoolean(RequiresClause != nullptr); if (RequiresClause) RequiresClause->Profile(ID, C, /*Canonical=*/true); } static Expr * canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC, QualType ConstrainedType) { // This is a bit ugly - we need to form a new immediately-declared // constraint that references the new parameter; this would ideally // require semantic analysis (e.g. template<C T> struct S {}; - the // converted arguments of C<T> could be an argument pack if C is // declared as template<typename... T> concept C = ...). // We don't have semantic analysis here so we dig deep into the // ready-made constraint expr and change the thing manually. ConceptSpecializationExpr *CSE; if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC)) CSE = cast<ConceptSpecializationExpr>(Fold->getLHS()); else CSE = cast<ConceptSpecializationExpr>(IDC); ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments(); SmallVector<TemplateArgument, 3> NewConverted; NewConverted.reserve(OldConverted.size()); if (OldConverted.front().getKind() == TemplateArgument::Pack) { // The case: // template<typename... T> concept C = true; // template<C<int> T> struct S; -> constraint is C<{T, int}> NewConverted.push_back(ConstrainedType); for (auto &Arg : OldConverted.front().pack_elements().drop_front(1)) NewConverted.push_back(Arg); TemplateArgument NewPack(NewConverted); NewConverted.clear(); NewConverted.push_back(NewPack); assert(OldConverted.size() == 1 && "Template parameter pack should be the last parameter"); } else { assert(OldConverted.front().getKind() == TemplateArgument::Type && "Unexpected first argument kind for immediately-declared " "constraint"); NewConverted.push_back(ConstrainedType); for (auto &Arg : OldConverted.drop_front(1)) NewConverted.push_back(Arg); } Expr *NewIDC = ConceptSpecializationExpr::Create( C, CSE->getNamedConcept(), NewConverted, nullptr, CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack()); if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC)) NewIDC = new (C) CXXFoldExpr(OrigFold->getType(), SourceLocation(), NewIDC, BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr, SourceLocation(), /*NumExpansions=*/None); return NewIDC; } TemplateTemplateParmDecl * ASTContext::getCanonicalTemplateTemplateParmDecl( TemplateTemplateParmDecl *TTP) const { // Check if we already have a canonical template template parameter. llvm::FoldingSetNodeID ID; CanonicalTemplateTemplateParm::Profile(ID, *this, TTP); void *InsertPos = nullptr; CanonicalTemplateTemplateParm *Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); if (Canonical) return Canonical->getParam(); // Build a canonical template parameter list. TemplateParameterList *Params = TTP->getTemplateParameters(); SmallVector<NamedDecl *, 4> CanonParams; CanonParams.reserve(Params->size()); for (TemplateParameterList::const_iterator P = Params->begin(), PEnd = Params->end(); P != PEnd; ++P) { if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(), TTP->getDepth(), TTP->getIndex(), nullptr, false, TTP->isParameterPack(), TTP->hasTypeConstraint(), TTP->isExpandedParameterPack() ? llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None); if (const auto *TC = TTP->getTypeConstraint()) { QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0); Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint( *this, TC->getImmediatelyDeclaredConstraint(), ParamAsArgument); TemplateArgumentListInfo CanonArgsAsWritten; if (auto *Args = TC->getTemplateArgsAsWritten()) for (const auto &ArgLoc : Args->arguments()) CanonArgsAsWritten.addArgument( TemplateArgumentLoc(ArgLoc.getArgument(), TemplateArgumentLocInfo())); NewTTP->setTypeConstraint( NestedNameSpecifierLoc(), DeclarationNameInfo(TC->getNamedConcept()->getDeclName(), SourceLocation()), /*FoundDecl=*/nullptr, // Actually canonicalizing a TemplateArgumentLoc is difficult so we // simply omit the ArgsAsWritten TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC); } CanonParams.push_back(NewTTP); } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { QualType T = getCanonicalType(NTTP->getType()); TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); NonTypeTemplateParmDecl *Param; if (NTTP->isExpandedParameterPack()) { SmallVector<QualType, 2> ExpandedTypes; SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); ExpandedTInfos.push_back( getTrivialTypeSourceInfo(ExpandedTypes.back())); } Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(), NTTP->getDepth(), NTTP->getPosition(), nullptr, T, TInfo, ExpandedTypes, ExpandedTInfos); } else { Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(), NTTP->getDepth(), NTTP->getPosition(), nullptr, T, NTTP->isParameterPack(), TInfo); } if (AutoType *AT = T->getContainedAutoType()) { if (AT->isConstrained()) { Param->setPlaceholderTypeConstraint( canonicalizeImmediatelyDeclaredConstraint( *this, NTTP->getPlaceholderTypeConstraint(), T)); } } CanonParams.push_back(Param); } else CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( cast<TemplateTemplateParmDecl>(*P))); } Expr *CanonRequiresClause = nullptr; if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause()) CanonRequiresClause = RequiresClause; TemplateTemplateParmDecl *CanonTTP = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), SourceLocation(), TTP->getDepth(), TTP->getPosition(), TTP->isParameterPack(), nullptr, TemplateParameterList::Create(*this, SourceLocation(), SourceLocation(), CanonParams, SourceLocation(), CanonRequiresClause)); // Get the new insert position for the node we care about. Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); assert(!Canonical && "Shouldn't be in the map!"); (void)Canonical; // Create the canonical template template parameter entry. Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); return CanonTTP; } CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { if (!LangOpts.CPlusPlus) return nullptr; switch (T.getCXXABI().getKind()) { case TargetCXXABI::Fuchsia: case TargetCXXABI::GenericARM: // Same as Itanium at this level case TargetCXXABI::iOS: case TargetCXXABI::iOS64: case TargetCXXABI::WatchOS: case TargetCXXABI::GenericAArch64: case TargetCXXABI::GenericMIPS: case TargetCXXABI::GenericItanium: case TargetCXXABI::WebAssembly: return CreateItaniumCXXABI(*this); case TargetCXXABI::Microsoft: return CreateMicrosoftCXXABI(*this); } llvm_unreachable("Invalid CXXABI type!"); } interp::Context &ASTContext::getInterpContext() { if (!InterpContext) { InterpContext.reset(new interp::Context(*this)); } return *InterpContext.get(); } static const LangASMap *getAddressSpaceMap(const TargetInfo &T, const LangOptions &LOpts) { if (LOpts.FakeAddressSpaceMap) { // The fake address space map must have a distinct entry for each // language-specific address space. static const unsigned FakeAddrSpaceMap[] = { 0, // Default 1, // opencl_global 3, // opencl_local 2, // opencl_constant 0, // opencl_private 4, // opencl_generic 5, // cuda_device 6, // cuda_constant 7, // cuda_shared 8, // ptr32_sptr 9, // ptr32_uptr 10 // ptr64 }; return &FakeAddrSpaceMap; } else { return &T.getAddressSpaceMap(); } } static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts) { switch (LangOpts.getAddressSpaceMapMangling()) { case LangOptions::ASMM_Target: return TI.useAddressSpaceMapMangling(); case LangOptions::ASMM_On: return true; case LangOptions::ASMM_Off: return false; } llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); } ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins) : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()), DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()), SubstTemplateTemplateParmPacks(this_()), CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts), SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)), XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles, LangOpts.XRayNeverInstrumentFiles, LangOpts.XRayAttrListFiles, SM)), PrintingPolicy(LOpts), Idents(idents), Selectors(sels), BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), CompCategories(this_()), LastSDM(nullptr, 0) { TUDecl = TranslationUnitDecl::Create(*this); TraversalScope = {TUDecl}; } ASTContext::~ASTContext() { // Release the DenseMaps associated with DeclContext objects. // FIXME: Is this the ideal solution? ReleaseDeclContextMaps(); // Call all of the deallocation functions on all of their targets. for (auto &Pair : Deallocations) (Pair.first)(Pair.second); // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed // because they can contain DenseMaps. for (llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) // Increment in loop to prevent using deallocated memory. if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) R->Destroy(*this); for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { // Increment in loop to prevent using deallocated memory. if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) R->Destroy(*this); } for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), AEnd = DeclAttrs.end(); A != AEnd; ++A) A->second->~AttrVec(); for (const auto &Value : ModuleInitializers) Value.second->~PerModuleInitializers(); for (APValue *Value : APValueCleanups) Value->~APValue(); } class ASTContext::ParentMap { /// Contains parents of a node. using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>; /// Maps from a node to its parents. This is used for nodes that have /// pointer identity only, which are more common and we can save space by /// only storing a unique pointer to them. using ParentMapPointers = llvm::DenseMap< const void *, llvm::PointerUnion<const Decl *, const Stmt *, ast_type_traits::DynTypedNode *, ParentVector *>>; /// Parent map for nodes without pointer identity. We store a full /// DynTypedNode for all keys. using ParentMapOtherNodes = llvm::DenseMap< ast_type_traits::DynTypedNode, llvm::PointerUnion<const Decl *, const Stmt *, ast_type_traits::DynTypedNode *, ParentVector *>>; ParentMapPointers PointerParents; ParentMapOtherNodes OtherParents; class ASTVisitor; static ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) { if (const auto *D = U.dyn_cast<const Decl *>()) return ast_type_traits::DynTypedNode::create(*D); if (const auto *S = U.dyn_cast<const Stmt *>()) return ast_type_traits::DynTypedNode::create(*S); return *U.get<ast_type_traits::DynTypedNode *>(); } template <typename NodeTy, typename MapTy> static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node, const MapTy &Map) { auto I = Map.find(Node); if (I == Map.end()) { return llvm::ArrayRef<ast_type_traits::DynTypedNode>(); } if (const auto *V = I->second.template dyn_cast<ParentVector *>()) { return llvm::makeArrayRef(*V); } return getSingleDynTypedNodeFromParentMap(I->second); } public: ParentMap(ASTContext &Ctx); ~ParentMap() { for (const auto &Entry : PointerParents) { if (Entry.second.is<ast_type_traits::DynTypedNode *>()) { delete Entry.second.get<ast_type_traits::DynTypedNode *>(); } else if (Entry.second.is<ParentVector *>()) { delete Entry.second.get<ParentVector *>(); } } for (const auto &Entry : OtherParents) { if (Entry.second.is<ast_type_traits::DynTypedNode *>()) { delete Entry.second.get<ast_type_traits::DynTypedNode *>(); } else if (Entry.second.is<ParentVector *>()) { delete Entry.second.get<ParentVector *>(); } } } DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) { if (Node.getNodeKind().hasPointerIdentity()) return getDynNodeFromMap(Node.getMemoizationData(), PointerParents); return getDynNodeFromMap(Node, OtherParents); } }; void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) { TraversalScope = TopLevelDecls; Parents.clear(); } void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const { Deallocations.push_back({Callback, Data}); } void ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { ExternalSource = std::move(Source); } void ASTContext::PrintStats() const { llvm::errs() << "\n*** AST Context Stats:\n"; llvm::errs() << " " << Types.size() << " types total.\n"; unsigned counts[] = { #define TYPE(Name, Parent) 0, #define ABSTRACT_TYPE(Name, Parent) #include "clang/AST/TypeNodes.inc" 0 // Extra }; for (unsigned i = 0, e = Types.size(); i != e; ++i) { Type *T = Types[i]; counts[(unsigned)T->getTypeClass()]++; } unsigned Idx = 0; unsigned TotalBytes = 0; #define TYPE(Name, Parent) \ if (counts[Idx]) \ llvm::errs() << " " << counts[Idx] << " " << #Name \ << " types, " << sizeof(Name##Type) << " each " \ << "(" << counts[Idx] * sizeof(Name##Type) \ << " bytes)\n"; \ TotalBytes += counts[Idx] * sizeof(Name##Type); \ ++Idx; #define ABSTRACT_TYPE(Name, Parent) #include "clang/AST/TypeNodes.inc" llvm::errs() << "Total bytes = " << TotalBytes << "\n"; // Implicit special member functions. llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" << NumImplicitDefaultConstructors << " implicit default constructors created\n"; llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" << NumImplicitCopyConstructors << " implicit copy constructors created\n"; if (getLangOpts().CPlusPlus) llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" << NumImplicitMoveConstructors << " implicit move constructors created\n"; llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" << NumImplicitCopyAssignmentOperators << " implicit copy assignment operators created\n"; if (getLangOpts().CPlusPlus) llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" << NumImplicitMoveAssignmentOperators << " implicit move assignment operators created\n"; llvm::errs() << NumImplicitDestructorsDeclared << "/" << NumImplicitDestructors << " implicit destructors created\n"; if (ExternalSource) { llvm::errs() << "\n"; ExternalSource->PrintStats(); } BumpAlloc.PrintStats(); } void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners) { if (NotifyListeners) if (auto *Listener = getASTMutationListener()) Listener->RedefinedHiddenDefinition(ND, M); MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M); } void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) { auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl())); if (It == MergedDefModules.end()) return; auto &Merged = It->second; llvm::DenseSet<Module*> Found; for (Module *&M : Merged) if (!Found.insert(M).second) M = nullptr; Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end()); } void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) { if (LazyInitializers.empty()) return; auto *Source = Ctx.getExternalSource(); assert(Source && "lazy initializers but no external source"); auto LazyInits = std::move(LazyInitializers); LazyInitializers.clear(); for (auto ID : LazyInits) Initializers.push_back(Source->GetExternalDecl(ID)); assert(LazyInitializers.empty() && "GetExternalDecl for lazy module initializer added more inits"); } void ASTContext::addModuleInitializer(Module *M, Decl *D) { // One special case: if we add a module initializer that imports another // module, and that module's only initializer is an ImportDecl, simplify. if (const auto *ID = dyn_cast<ImportDecl>(D)) { auto It = ModuleInitializers.find(ID->getImportedModule()); // Maybe the ImportDecl does nothing at all. (Common case.) if (It == ModuleInitializers.end()) return; // Maybe the ImportDecl only imports another ImportDecl. auto &Imported = *It->second; if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) { Imported.resolve(*this); auto *OnlyDecl = Imported.Initializers.front(); if (isa<ImportDecl>(OnlyDecl)) D = OnlyDecl; } } auto *&Inits = ModuleInitializers[M]; if (!Inits) Inits = new (*this) PerModuleInitializers; Inits->Initializers.push_back(D); } void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) { auto *&Inits = ModuleInitializers[M]; if (!Inits) Inits = new (*this) PerModuleInitializers; Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), IDs.begin(), IDs.end()); } ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) { auto It = ModuleInitializers.find(M); if (It == ModuleInitializers.end()) return None; auto *Inits = It->second; Inits->resolve(*this); return Inits->Initializers; } ExternCContextDecl *ASTContext::getExternCContextDecl() const { if (!ExternCContext) ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl()); return ExternCContext; } BuiltinTemplateDecl * ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const { auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK); BuiltinTemplate->setImplicit(); TUDecl->addDecl(BuiltinTemplate); return BuiltinTemplate; } BuiltinTemplateDecl * ASTContext::getMakeIntegerSeqDecl() const { if (!MakeIntegerSeqDecl) MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq, getMakeIntegerSeqName()); return MakeIntegerSeqDecl; } BuiltinTemplateDecl * ASTContext::getTypePackElementDecl() const { if (!TypePackElementDecl) TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element, getTypePackElementName()); return TypePackElementDecl; } RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK) const { SourceLocation Loc; RecordDecl *NewDecl; if (getLangOpts().CPlusPlus) NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, &Idents.get(Name)); else NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, &Idents.get(Name)); NewDecl->setImplicit(); NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit( const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default)); return NewDecl; } TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, StringRef Name) const { TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); TypedefDecl *NewDecl = TypedefDecl::Create( const_cast<ASTContext &>(*this), getTranslationUnitDecl(), SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); NewDecl->setImplicit(); return NewDecl; } TypedefDecl *ASTContext::getInt128Decl() const { if (!Int128Decl) Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); return Int128Decl; } TypedefDecl *ASTContext::getUInt128Decl() const { if (!UInt128Decl) UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); return UInt128Decl; } void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { auto *Ty = new (*this, TypeAlignment) BuiltinType(K); R = CanQualType::CreateUnsafe(QualType(Ty, 0)); Types.push_back(Ty); } void ASTContext::InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget) { assert((!this->Target || this->Target == &Target) && "Incorrect target reinitialization"); assert(VoidTy.isNull() && "Context reinitialized?"); this->Target = &Target; this->AuxTarget = AuxTarget; ABI.reset(createCXXABI(Target)); AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); // C99 6.2.5p19. InitBuiltinType(VoidTy, BuiltinType::Void); // C99 6.2.5p2. InitBuiltinType(BoolTy, BuiltinType::Bool); // C99 6.2.5p3. if (LangOpts.CharIsSigned) InitBuiltinType(CharTy, BuiltinType::Char_S); else InitBuiltinType(CharTy, BuiltinType::Char_U); // C99 6.2.5p4. InitBuiltinType(SignedCharTy, BuiltinType::SChar); InitBuiltinType(ShortTy, BuiltinType::Short); InitBuiltinType(IntTy, BuiltinType::Int); InitBuiltinType(LongTy, BuiltinType::Long); InitBuiltinType(LongLongTy, BuiltinType::LongLong); // C99 6.2.5p6. InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); // C99 6.2.5p10. InitBuiltinType(FloatTy, BuiltinType::Float); InitBuiltinType(DoubleTy, BuiltinType::Double); InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); // GNU extension, __float128 for IEEE quadruple precision InitBuiltinType(Float128Ty, BuiltinType::Float128); // C11 extension ISO/IEC TS 18661-3 InitBuiltinType(Float16Ty, BuiltinType::Float16); // ISO/IEC JTC1 SC22 WG14 N1169 Extension InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum); InitBuiltinType(AccumTy, BuiltinType::Accum); InitBuiltinType(LongAccumTy, BuiltinType::LongAccum); InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum); InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum); InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum); InitBuiltinType(ShortFractTy, BuiltinType::ShortFract); InitBuiltinType(FractTy, BuiltinType::Fract); InitBuiltinType(LongFractTy, BuiltinType::LongFract); InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract); InitBuiltinType(UnsignedFractTy, BuiltinType::UFract); InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract); InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum); InitBuiltinType(SatAccumTy, BuiltinType::SatAccum); InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum); InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum); InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum); InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum); InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract); InitBuiltinType(SatFractTy, BuiltinType::SatFract); InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract); InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract); InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract); InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract); // GNU extension, 128-bit integers. InitBuiltinType(Int128Ty, BuiltinType::Int128); InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); // C++ 3.9.1p5 if (TargetInfo::isTypeSigned(Target.getWCharType())) InitBuiltinType(WCharTy, BuiltinType::WChar_S); else // -fshort-wchar makes wchar_t be unsigned. InitBuiltinType(WCharTy, BuiltinType::WChar_U); if (LangOpts.CPlusPlus && LangOpts.WChar) WideCharTy = WCharTy; else { // C99 (or C++ using -fno-wchar). WideCharTy = getFromTargetType(Target.getWCharType()); } WIntTy = getFromTargetType(Target.getWIntType()); // C++20 (proposed) InitBuiltinType(Char8Ty, BuiltinType::Char8); if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ InitBuiltinType(Char16Ty, BuiltinType::Char16); else // C99 Char16Ty = getFromTargetType(Target.getChar16Type()); if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ InitBuiltinType(Char32Ty, BuiltinType::Char32); else // C99 Char32Ty = getFromTargetType(Target.getChar32Type()); // Placeholder type for type-dependent expressions whose type is // completely unknown. No code should ever check a type against // DependentTy and users should never see it; however, it is here to // help diagnose failures to properly check for type-dependent // expressions. InitBuiltinType(DependentTy, BuiltinType::Dependent); // Placeholder type for functions. InitBuiltinType(OverloadTy, BuiltinType::Overload); // Placeholder type for bound members. InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); // Placeholder type for pseudo-objects. InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); // "any" type; useful for debugger-like clients. InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); // Placeholder type for unbridged ARC casts. InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); // Placeholder type for builtin functions. InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); // Placeholder type for OMP array sections. if (LangOpts.OpenMP) InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection); // C99 6.2.5p11. FloatComplexTy = getComplexType(FloatTy); DoubleComplexTy = getComplexType(DoubleTy); LongDoubleComplexTy = getComplexType(LongDoubleTy); Float128ComplexTy = getComplexType(Float128Ty); // Builtin types for 'id', 'Class', and 'SEL'. InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); if (LangOpts.OpenCL) { #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ InitBuiltinType(SingletonId, BuiltinType::Id); #include "clang/Basic/OpenCLImageTypes.def" InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent); InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ InitBuiltinType(Id##Ty, BuiltinType::Id); #include "clang/Basic/OpenCLExtensionTypes.def" } if (Target.hasAArch64SVETypes()) { #define SVE_TYPE(Name, Id, SingletonId) \ InitBuiltinType(SingletonId, BuiltinType::Id); #include "clang/Basic/AArch64SVEACLETypes.def" } // Builtin type for __objc_yes and __objc_no ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? SignedCharTy : BoolTy); ObjCConstantStringType = QualType(); ObjCSuperType = QualType(); // void * type if (LangOpts.OpenCLVersion >= 200) { auto Q = VoidTy.getQualifiers(); Q.setAddressSpace(LangAS::opencl_generic); VoidPtrTy = getPointerType(getCanonicalType( getQualifiedType(VoidTy.getUnqualifiedType(), Q))); } else { VoidPtrTy = getPointerType(VoidTy); } // nullptr type (C++0x 2.14.7) InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 InitBuiltinType(HalfTy, BuiltinType::Half); // Scaffold: cbit and qbit types added here for initialization InitBuiltinType(AbitTy, BuiltinType::Abit); InitBuiltinType(CbitTy, BuiltinType::Cbit); InitBuiltinType(QbitTy, BuiltinType::Qbit); // RKQC: qint added for initialization InitBuiltinType(QintTy, BuiltinType::Qint); InitBuiltinType(zzBitTy, BuiltinType::zzBit); InitBuiltinType(zgBitTy, BuiltinType::zgBit); InitBuiltinType(ooBitTy, BuiltinType::ooBit); InitBuiltinType(ogBitTy, BuiltinType::ogBit); // Builtin type used to help define __builtin_va_list. VaListTagDecl = nullptr; } DiagnosticsEngine &ASTContext::getDiagnostics() const { return SourceMgr.getDiagnostics(); } AttrVec& ASTContext::getDeclAttrs(const Decl *D) { AttrVec *&Result = DeclAttrs[D]; if (!Result) { void *Mem = Allocate(sizeof(AttrVec)); Result = new (Mem) AttrVec; } return *Result; } /// Erase the attributes corresponding to the given declaration. void ASTContext::eraseDeclAttrs(const Decl *D) { llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); if (Pos != DeclAttrs.end()) { Pos->second->~AttrVec(); DeclAttrs.erase(Pos); } } // FIXME: Remove ? MemberSpecializationInfo * ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { assert(Var->isStaticDataMember() && "Not a static data member"); return getTemplateOrSpecializationInfo(Var) .dyn_cast<MemberSpecializationInfo *>(); } ASTContext::TemplateOrSpecializationInfo ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = TemplateOrInstantiation.find(Var); if (Pos == TemplateOrInstantiation.end()) return {}; return Pos->second; } void ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation) { assert(Inst->isStaticDataMember() && "Not a static data member"); assert(Tmpl->isStaticDataMember() && "Not a static data member"); setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( Tmpl, TSK, PointOfInstantiation)); } void ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI) { assert(!TemplateOrInstantiation[Inst] && "Already noted what the variable was instantiated from"); TemplateOrInstantiation[Inst] = TSI; } NamedDecl * ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) { auto Pos = InstantiatedFromUsingDecl.find(UUD); if (Pos == InstantiatedFromUsingDecl.end()) return nullptr; return Pos->second; } void ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) { assert((isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern)) && "pattern decl is not a using decl"); assert((isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) && "instantiation did not produce a using decl"); assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); InstantiatedFromUsingDecl[Inst] = Pattern; } UsingShadowDecl * ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos = InstantiatedFromUsingShadowDecl.find(Inst); if (Pos == InstantiatedFromUsingShadowDecl.end()) return nullptr; return Pos->second; } void ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern) { assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); InstantiatedFromUsingShadowDecl[Inst] = Pattern; } FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos = InstantiatedFromUnnamedFieldDecl.find(Field); if (Pos == InstantiatedFromUnnamedFieldDecl.end()) return nullptr; return Pos->second; } void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl) { assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); assert(!InstantiatedFromUnnamedFieldDecl[Inst] && "Already noted what unnamed field was instantiated from"); InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; } ASTContext::overridden_cxx_method_iterator ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { return overridden_methods(Method).begin(); } ASTContext::overridden_cxx_method_iterator ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { return overridden_methods(Method).end(); } unsigned ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { auto Range = overridden_methods(Method); return Range.end() - Range.begin(); } ASTContext::overridden_method_range ASTContext::overridden_methods(const CXXMethodDecl *Method) const { llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos = OverriddenMethods.find(Method->getCanonicalDecl()); if (Pos == OverriddenMethods.end()) return overridden_method_range(nullptr, nullptr); return overridden_method_range(Pos->second.begin(), Pos->second.end()); } void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden) { assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); OverriddenMethods[Method].push_back(Overridden); } void ASTContext::getOverriddenMethods( const NamedDecl *D, SmallVectorImpl<const NamedDecl *> &Overridden) const { assert(D); if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { Overridden.append(overridden_methods_begin(CXXMethod), overridden_methods_end(CXXMethod)); return; } const auto *Method = dyn_cast<ObjCMethodDecl>(D); if (!Method) return; SmallVector<const ObjCMethodDecl *, 8> OverDecls; Method->getOverriddenMethods(OverDecls); Overridden.append(OverDecls.begin(), OverDecls.end()); } void ASTContext::addedLocalImportDecl(ImportDecl *Import) { assert(!Import->NextLocalImport && "Import declaration already in the chain"); assert(!Import->isFromASTFile() && "Non-local import declaration"); if (!FirstLocalImport) { FirstLocalImport = Import; LastLocalImport = Import; return; } LastLocalImport->NextLocalImport = Import; LastLocalImport = Import; } //===----------------------------------------------------------------------===// // Type Sizing and Analysis //===----------------------------------------------------------------------===// /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified /// scalar floating point type. const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { switch (T->castAs<BuiltinType>()->getKind()) { default: llvm_unreachable("Not a floating point type!"); case BuiltinType::Float16: case BuiltinType::Half: return Target->getHalfFormat(); case BuiltinType::Float: return Target->getFloatFormat(); case BuiltinType::Double: return Target->getDoubleFormat(); case BuiltinType::LongDouble: if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) return AuxTarget->getLongDoubleFormat(); return Target->getLongDoubleFormat(); case BuiltinType::Float128: if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) return AuxTarget->getFloat128Format(); return Target->getFloat128Format(); } } CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { unsigned Align = Target->getCharWidth(); bool UseAlignAttrOnly = false; if (unsigned AlignFromAttr = D->getMaxAlignment()) { Align = AlignFromAttr; // __attribute__((aligned)) can increase or decrease alignment // *except* on a struct or struct member, where it only increases // alignment unless 'packed' is also specified. // // It is an error for alignas to decrease alignment, so we can // ignore that possibility; Sema should diagnose it. if (isa<FieldDecl>(D)) { UseAlignAttrOnly = D->hasAttr<PackedAttr>() || cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); } else { UseAlignAttrOnly = true; } } else if (isa<FieldDecl>(D)) UseAlignAttrOnly = D->hasAttr<PackedAttr>() || cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); // If we're using the align attribute only, just ignore everything // else about the declaration and its type. if (UseAlignAttrOnly) { // do nothing } else if (const auto *VD = dyn_cast<ValueDecl>(D)) { QualType T = VD->getType(); if (const auto *RT = T->getAs<ReferenceType>()) { if (ForAlignof) T = RT->getPointeeType(); else T = getPointerType(RT->getPointeeType()); } QualType BaseT = getBaseElementType(T); if (T->isFunctionType()) Align = getTypeInfoImpl(T.getTypePtr()).Align; else if (!BaseT->isIncompleteType()) { // Adjust alignments of declarations with array type by the // large-array alignment on the target. if (const ArrayType *arrayType = getAsArrayType(T)) { unsigned MinWidth = Target->getLargeArrayMinWidth(); if (!ForAlignof && MinWidth) { if (isa<VariableArrayType>(arrayType)) Align = std::max(Align, Target->getLargeArrayAlign()); else if (isa<ConstantArrayType>(arrayType) && MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) Align = std::max(Align, Target->getLargeArrayAlign()); } } Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); if (BaseT.getQualifiers().hasUnaligned()) Align = Target->getCharWidth(); if (const auto *VD = dyn_cast<VarDecl>(D)) { if (VD->hasGlobalStorage() && !ForAlignof) { uint64_t TypeSize = getTypeSize(T.getTypePtr()); Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize)); } } } // Fields can be subject to extra alignment constraints, like if // the field is packed, the struct is packed, or the struct has a // a max-field-alignment constraint (#pragma pack). So calculate // the actual alignment of the field within the struct, and then // (as we're expected to) constrain that by the alignment of the type. if (const auto *Field = dyn_cast<FieldDecl>(VD)) { const RecordDecl *Parent = Field->getParent(); // We can only produce a sensible answer if the record is valid. if (!Parent->isInvalidDecl()) { const ASTRecordLayout &Layout = getASTRecordLayout(Parent); // Start with the record's overall alignment. unsigned FieldAlign = toBits(Layout.getAlignment()); // Use the GCD of that and the offset within the record. uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); if (Offset > 0) { // Alignment is always a power of 2, so the GCD will be a power of 2, // which means we get to do this crazy thing instead of Euclid's. uint64_t LowBitOfOffset = Offset & (~Offset + 1); if (LowBitOfOffset < FieldAlign) FieldAlign = static_cast<unsigned>(LowBitOfOffset); } Align = std::min(Align, FieldAlign); } } } return toCharUnitsFromBits(Align); } // getTypeInfoDataSizeInChars - Return the size of a type, in // chars. If the type is a record, its data size is returned. This is // the size of the memcpy that's performed when assigning this type // using a trivial copy/move assignment operator. std::pair<CharUnits, CharUnits> ASTContext::getTypeInfoDataSizeInChars(QualType T) const { std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T); // In C++, objects can sometimes be allocated into the tail padding // of a base-class subobject. We decide whether that's possible // during class layout, so here we can just trust the layout results. if (getLangOpts().CPlusPlus) { if (const auto *RT = T->getAs<RecordType>()) { const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); sizeAndAlign.first = layout.getDataSize(); } } return sizeAndAlign; } /// getConstantArrayInfoInChars - Performing the computation in CharUnits /// instead of in bits prevents overflowing the uint64_t for some large arrays. std::pair<CharUnits, CharUnits> static getConstantArrayInfoInChars(const ASTContext &Context, const ConstantArrayType *CAT) { std::pair<CharUnits, CharUnits> EltInfo = Context.getTypeInfoInChars(CAT->getElementType()); uint64_t Size = CAT->getSize().getZExtValue(); assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <= (uint64_t)(-1)/Size) && "Overflow in array type char size evaluation"); uint64_t Width = EltInfo.first.getQuantity() * Size; unsigned Align = EltInfo.second.getQuantity(); if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || Context.getTargetInfo().getPointerWidth(0) == 64) Width = llvm::alignTo(Width, Align); return std::make_pair(CharUnits::fromQuantity(Width), CharUnits::fromQuantity(Align)); } std::pair<CharUnits, CharUnits> ASTContext::getTypeInfoInChars(const Type *T) const { if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) return getConstantArrayInfoInChars(*this, CAT); TypeInfo Info = getTypeInfo(T); return std::make_pair(toCharUnitsFromBits(Info.Width), toCharUnitsFromBits(Info.Align)); } std::pair<CharUnits, CharUnits> ASTContext::getTypeInfoInChars(QualType T) const { return getTypeInfoInChars(T.getTypePtr()); } bool ASTContext::isAlignmentRequired(const Type *T) const { return getTypeInfo(T).AlignIsRequired; } bool ASTContext::isAlignmentRequired(QualType T) const { return isAlignmentRequired(T.getTypePtr()); } unsigned ASTContext::getTypeAlignIfKnown(QualType T) const { // An alignment on a typedef overrides anything else. if (const auto *TT = T->getAs<TypedefType>()) if (unsigned Align = TT->getDecl()->getMaxAlignment()) return Align; // If we have an (array of) complete type, we're done. T = getBaseElementType(T); if (!T->isIncompleteType()) return getTypeAlign(T); // If we had an array type, its element type might be a typedef // type with an alignment attribute. if (const auto *TT = T->getAs<TypedefType>()) if (unsigned Align = TT->getDecl()->getMaxAlignment()) return Align; // Otherwise, see if the declaration of the type had an attribute. if (const auto *TT = T->getAs<TagType>()) return TT->getDecl()->getMaxAlignment(); return 0; } TypeInfo ASTContext::getTypeInfo(const Type *T) const { TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); if (I != MemoizedTypeInfo.end()) return I->second; // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. TypeInfo TI = getTypeInfoImpl(T); MemoizedTypeInfo[T] = TI; return TI; } /// getTypeInfoImpl - Return the size of the specified type, in bits. This /// method does not work on incomplete types. /// /// FIXME: Pointers into different addr spaces could have different sizes and /// alignment requirements: getPointerInfo should take an AddrSpace, this /// should take a QualType, &c. TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { uint64_t Width = 0; unsigned Align = 8; bool AlignIsRequired = false; unsigned AS = 0; switch (T->getTypeClass()) { #define TYPE(Class, Base) #define ABSTRACT_TYPE(Class, Base) #define NON_CANONICAL_TYPE(Class, Base) #define DEPENDENT_TYPE(Class, Base) case Type::Class: #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ case Type::Class: \ assert(!T->isDependentType() && "should not see dependent types here"); \ return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); #include "clang/AST/TypeNodes.inc" llvm_unreachable("Should not see dependent types"); case Type::FunctionNoProto: case Type::FunctionProto: // GCC extension: alignof(function) = 32 bits Width = 0; Align = 32; break; case Type::IncompleteArray: case Type::VariableArray: Width = 0; Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); break; case Type::ConstantArray: { const auto *CAT = cast<ConstantArrayType>(T); TypeInfo EltInfo = getTypeInfo(CAT->getElementType()); uint64_t Size = CAT->getSize().getZExtValue(); assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && "Overflow in array type bit size evaluation"); Width = EltInfo.Width * Size; Align = EltInfo.Align; if (!getTargetInfo().getCXXABI().isMicrosoft() || getTargetInfo().getPointerWidth(0) == 64) Width = llvm::alignTo(Width, Align); break; } case Type::ExtVector: case Type::Vector: { const auto *VT = cast<VectorType>(T); TypeInfo EltInfo = getTypeInfo(VT->getElementType()); Width = EltInfo.Width * VT->getNumElements(); Align = Width; // If the alignment is not a power of 2, round up to the next power of 2. // This happens for non-power-of-2 length vectors. if (Align & (Align-1)) { Align = llvm::NextPowerOf2(Align); Width = llvm::alignTo(Width, Align); } // Adjust the alignment based on the target max. uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); if (TargetVectorAlign && TargetVectorAlign < Align) Align = TargetVectorAlign; break; } case Type::Builtin: switch (cast<BuiltinType>(T)->getKind()) { default: llvm_unreachable("Unknown builtin type!"); case BuiltinType::Void: // GCC extension: alignof(void) = 8 bits. Width = 0; Align = 8; break; case BuiltinType::Bool: Width = Target->getBoolWidth(); Align = Target->getBoolAlign(); break; case BuiltinType::Char_S: case BuiltinType::Char_U: case BuiltinType::UChar: case BuiltinType::SChar: case BuiltinType::Char8: Width = Target->getCharWidth(); Align = Target->getCharAlign(); break; case BuiltinType::WChar_S: case BuiltinType::WChar_U: Width = Target->getWCharWidth(); Align = Target->getWCharAlign(); break; case BuiltinType::Char16: Width = Target->getChar16Width(); Align = Target->getChar16Align(); break; case BuiltinType::Char32: Width = Target->getChar32Width(); Align = Target->getChar32Align(); break; case BuiltinType::UShort: case BuiltinType::Short: Width = Target->getShortWidth(); Align = Target->getShortAlign(); break; case BuiltinType::UInt: case BuiltinType::Int: Width = Target->getIntWidth(); Align = Target->getIntAlign(); break; case BuiltinType::ULong: case BuiltinType::Long: Width = Target->getLongWidth(); Align = Target->getLongAlign(); break; case BuiltinType::ULongLong: case BuiltinType::LongLong: Width = Target->getLongLongWidth(); Align = Target->getLongLongAlign(); break; case BuiltinType::Int128: case BuiltinType::UInt128: Width = 128; Align = 128; // int128_t is 128-bit aligned on all targets. break; case BuiltinType::ShortAccum: case BuiltinType::UShortAccum: case BuiltinType::SatShortAccum: case BuiltinType::SatUShortAccum: Width = Target->getShortAccumWidth(); Align = Target->getShortAccumAlign(); break; case BuiltinType::Accum: case BuiltinType::UAccum: case BuiltinType::SatAccum: case BuiltinType::SatUAccum: Width = Target->getAccumWidth(); Align = Target->getAccumAlign(); break; case BuiltinType::LongAccum: case BuiltinType::ULongAccum: case BuiltinType::SatLongAccum: case BuiltinType::SatULongAccum: Width = Target->getLongAccumWidth(); Align = Target->getLongAccumAlign(); break; case BuiltinType::ShortFract: case BuiltinType::UShortFract: case BuiltinType::SatShortFract: case BuiltinType::SatUShortFract: Width = Target->getShortFractWidth(); Align = Target->getShortFractAlign(); break; case BuiltinType::Fract: case BuiltinType::UFract: case BuiltinType::SatFract: case BuiltinType::SatUFract: Width = Target->getFractWidth(); Align = Target->getFractAlign(); break; case BuiltinType::LongFract: case BuiltinType::ULongFract: case BuiltinType::SatLongFract: case BuiltinType::SatULongFract: Width = Target->getLongFractWidth(); Align = Target->getLongFractAlign(); break; case BuiltinType::Float16: case BuiltinType::Half: if (Target->hasFloat16Type() || !getLangOpts().OpenMP || !getLangOpts().OpenMPIsDevice) { Width = Target->getHalfWidth(); Align = Target->getHalfAlign(); } else { assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && "Expected OpenMP device compilation."); Width = AuxTarget->getHalfWidth(); Align = AuxTarget->getHalfAlign(); } break; case BuiltinType::Float: Width = Target->getFloatWidth(); Align = Target->getFloatAlign(); break; case BuiltinType::Double: Width = Target->getDoubleWidth(); Align = Target->getDoubleAlign(); break; case BuiltinType::LongDouble: if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() || Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) { Width = AuxTarget->getLongDoubleWidth(); Align = AuxTarget->getLongDoubleAlign(); } else { Width = Target->getLongDoubleWidth(); Align = Target->getLongDoubleAlign(); } break; case BuiltinType::Float128: if (Target->hasFloat128Type() || !getLangOpts().OpenMP || !getLangOpts().OpenMPIsDevice) { Width = Target->getFloat128Width(); Align = Target->getFloat128Align(); } else { assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && "Expected OpenMP device compilation."); Width = AuxTarget->getFloat128Width(); Align = AuxTarget->getFloat128Align(); } break; case BuiltinType::NullPtr: Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) Align = Target->getPointerAlign(0); // == sizeof(void*) break; case BuiltinType::ObjCId: case BuiltinType::ObjCClass: case BuiltinType::ObjCSel: Width = Target->getPointerWidth(0); Align = Target->getPointerAlign(0); break; // Scaffold types case BuiltinType::Abit: Width = Target->getAbitWidth(); Align = Target->getAbitAlign(); break; case BuiltinType::Cbit: Width = Target->getCbitWidth(); Align = Target->getCbitAlign(); break; case BuiltinType::Qbit: Width = Target->getQbitWidth(); Align = Target->getQbitAlign(); break; case BuiltinType::Qint: Width = Target->getQintWidth(); Align = Target->getQintAlign(); break; case BuiltinType::OCLSampler: case BuiltinType::OCLEvent: case BuiltinType::OCLClkEvent: case BuiltinType::OCLQueue: case BuiltinType::OCLReserveID: #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ case BuiltinType::Id: #include "clang/Basic/OpenCLImageTypes.def" #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ case BuiltinType::Id: #include "clang/Basic/OpenCLExtensionTypes.def" AS = getTargetAddressSpace( Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T))); Width = Target->getPointerWidth(AS); Align = Target->getPointerAlign(AS); break; // The SVE types are effectively target-specific. The length of an // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple // of 128 bits. There is one predicate bit for each vector byte, so the // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits. // // Because the length is only known at runtime, we use a dummy value // of 0 for the static length. The alignment values are those defined // by the Procedure Call Standard for the Arm Architecture. #define SVE_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, IsSigned, IsFP)\ case BuiltinType::Id: \ Width = 0; \ Align = 128; \ break; #define SVE_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \ case BuiltinType::Id: \ Width = 0; \ Align = 16; \ break; #include "clang/Basic/AArch64SVEACLETypes.def" } break; case Type::ObjCObjectPointer: Width = Target->getPointerWidth(0); Align = Target->getPointerAlign(0); break; case Type::BlockPointer: AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType()); Width = Target->getPointerWidth(AS); Align = Target->getPointerAlign(AS); break; case Type::LValueReference: case Type::RValueReference: // alignof and sizeof should never enter this code path here, so we go // the pointer route. AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType()); Width = Target->getPointerWidth(AS); Align = Target->getPointerAlign(AS); break; case Type::Pointer: AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); Width = Target->getPointerWidth(AS); Align = Target->getPointerAlign(AS); break; case Type::MemberPointer: { const auto *MPT = cast<MemberPointerType>(T); CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT); Width = MPI.Width; Align = MPI.Align; break; } case Type::Complex: { // Complex types have the same alignment as their elements, but twice the // size. TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); Width = EltInfo.Width * 2; Align = EltInfo.Align; break; } case Type::ObjCObject: return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); case Type::Adjusted: case Type::Decayed: return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); case Type::ObjCInterface: { const auto *ObjCI = cast<ObjCInterfaceType>(T); const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); Width = toBits(Layout.getSize()); Align = toBits(Layout.getAlignment()); break; } case Type::Record: case Type::Enum: { const auto *TT = cast<TagType>(T); if (TT->getDecl()->isInvalidDecl()) { Width = 8; Align = 8; break; } if (const auto *ET = dyn_cast<EnumType>(TT)) { const EnumDecl *ED = ET->getDecl(); TypeInfo Info = getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType()); if (unsigned AttrAlign = ED->getMaxAlignment()) { Info.Align = AttrAlign; Info.AlignIsRequired = true; } return Info; } const auto *RT = cast<RecordType>(TT); const RecordDecl *RD = RT->getDecl(); const ASTRecordLayout &Layout = getASTRecordLayout(RD); Width = toBits(Layout.getSize()); Align = toBits(Layout.getAlignment()); AlignIsRequired = RD->hasAttr<AlignedAttr>(); break; } case Type::SubstTemplateTypeParm: return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> getReplacementType().getTypePtr()); case Type::Auto: case Type::DeducedTemplateSpecialization: { const auto *A = cast<DeducedType>(T); assert(!A->getDeducedType().isNull() && "cannot request the size of an undeduced or dependent auto type"); return getTypeInfo(A->getDeducedType().getTypePtr()); } case Type::Paren: return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); case Type::MacroQualified: return getTypeInfo( cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr()); case Type::ObjCTypeParam: return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr()); case Type::Typedef: { const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); // If the typedef has an aligned attribute on it, it overrides any computed // alignment we have. This violates the GCC documentation (which says that // attribute(aligned) can only round up) but matches its implementation. if (unsigned AttrAlign = Typedef->getMaxAlignment()) { Align = AttrAlign; AlignIsRequired = true; } else { Align = Info.Align; AlignIsRequired = Info.AlignIsRequired; } Width = Info.Width; break; } case Type::Elaborated: return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); case Type::Attributed: return getTypeInfo( cast<AttributedType>(T)->getEquivalentType().getTypePtr()); case Type::Atomic: { // Start with the base type information. TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); Width = Info.Width; Align = Info.Align; if (!Width) { // An otherwise zero-sized type should still generate an // atomic operation. Width = Target->getCharWidth(); assert(Align); } else if (Width <= Target->getMaxAtomicPromoteWidth()) { // If the size of the type doesn't exceed the platform's max // atomic promotion width, make the size and alignment more // favorable to atomic operations: // Round the size up to a power of 2. if (!llvm::isPowerOf2_64(Width)) Width = llvm::NextPowerOf2(Width); // Set the alignment equal to the size. Align = static_cast<unsigned>(Width); } } break; case Type::Pipe: Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global)); Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global)); break; } assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); return TypeInfo(Width, Align, AlignIsRequired); } unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const { UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T); if (I != MemoizedUnadjustedAlign.end()) return I->second; unsigned UnadjustedAlign; if (const auto *RT = T->getAs<RecordType>()) { const RecordDecl *RD = RT->getDecl(); const ASTRecordLayout &Layout = getASTRecordLayout(RD); UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) { const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); } else { UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType()); } MemoizedUnadjustedAlign[T] = UnadjustedAlign; return UnadjustedAlign; } unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const { unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign(); // Target ppc64 with QPX: simd default alignment for pointer to double is 32. if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 || getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) && getTargetInfo().getABI() == "elfv1-qpx" && T->isSpecificBuiltinType(BuiltinType::Double)) SimdAlign = 256; return SimdAlign; } /// toCharUnitsFromBits - Convert a size in bits to a size in characters. CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { return CharUnits::fromQuantity(BitSize / getCharWidth()); } /// toBits - Convert a size in characters to a size in characters. int64_t ASTContext::toBits(CharUnits CharSize) const { return CharSize.getQuantity() * getCharWidth(); } /// getTypeSizeInChars - Return the size of the specified type, in characters. /// This method does not work on incomplete types. CharUnits ASTContext::getTypeSizeInChars(QualType T) const { return getTypeInfoInChars(T).first; } CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { return getTypeInfoInChars(T).first; } /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in /// characters. This method does not work on incomplete types. CharUnits ASTContext::getTypeAlignInChars(QualType T) const { return toCharUnitsFromBits(getTypeAlign(T)); } CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { return toCharUnitsFromBits(getTypeAlign(T)); } /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a /// type, in characters, before alignment adustments. This method does /// not work on incomplete types. CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const { return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); } CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const { return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); } /// getPreferredTypeAlign - Return the "preferred" alignment of the specified /// type for the current target in bits. This can be different than the ABI /// alignment in cases where it is beneficial for performance to overalign /// a data type. unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { TypeInfo TI = getTypeInfo(T); unsigned ABIAlign = TI.Align; T = T->getBaseElementTypeUnsafe(); // The preferred alignment of member pointers is that of a pointer. if (T->isMemberPointerType()) return getPreferredTypeAlign(getPointerDiffType().getTypePtr()); if (!Target->allowsLargerPreferedTypeAlignment()) return ABIAlign; // Double and long long should be naturally aligned if possible. if (const auto *CT = T->getAs<ComplexType>()) T = CT->getElementType().getTypePtr(); if (const auto *ET = T->getAs<EnumType>()) T = ET->getDecl()->getIntegerType().getTypePtr(); if (T->isSpecificBuiltinType(BuiltinType::Double) || T->isSpecificBuiltinType(BuiltinType::LongLong) || T->isSpecificBuiltinType(BuiltinType::ULongLong)) // Don't increase the alignment if an alignment attribute was specified on a // typedef declaration. if (!TI.AlignIsRequired) return std::max(ABIAlign, (unsigned)getTypeSize(T)); return ABIAlign; } /// getTargetDefaultAlignForAttributeAligned - Return the default alignment /// for __attribute__((aligned)) on this target, to be used if no alignment /// value is specified. unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const { return getTargetInfo().getDefaultAlignForAttributeAligned(); } /// getAlignOfGlobalVar - Return the alignment in bits that should be given /// to a global variable of the specified type. unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { uint64_t TypeSize = getTypeSize(T.getTypePtr()); return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize)); } /// getAlignOfGlobalVarInChars - Return the alignment in characters that /// should be given to a global variable of the specified type. CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { return toCharUnitsFromBits(getAlignOfGlobalVar(T)); } CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const { CharUnits Offset = CharUnits::Zero(); const ASTRecordLayout *Layout = &getASTRecordLayout(RD); while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) { Offset += Layout->getBaseClassOffset(Base); Layout = &getASTRecordLayout(Base); } return Offset; } /// DeepCollectObjCIvars - /// This routine first collects all declared, but not synthesized, ivars in /// super class and then collects all ivars, including those synthesized for /// current class. This routine is used for implementation of current class /// when all ivars, declared and synthesized are known. void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) DeepCollectObjCIvars(SuperClass, false, Ivars); if (!leafClass) { for (const auto *I : OI->ivars()) Ivars.push_back(I); } else { auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI); for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; Iv= Iv->getNextIvar()) Ivars.push_back(Iv); } } /// CollectInheritedProtocols - Collect all protocols in current class and /// those inherited by it. void ASTContext::CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { // We can use protocol_iterator here instead of // all_referenced_protocol_iterator since we are walking all categories. for (auto *Proto : OI->all_referenced_protocols()) { CollectInheritedProtocols(Proto, Protocols); } // Categories of this Interface. for (const auto *Cat : OI->visible_categories()) CollectInheritedProtocols(Cat, Protocols); if (ObjCInterfaceDecl *SD = OI->getSuperClass()) while (SD) { CollectInheritedProtocols(SD, Protocols); SD = SD->getSuperClass(); } } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { for (auto *Proto : OC->protocols()) { CollectInheritedProtocols(Proto, Protocols); } } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { // Insert the protocol. if (!Protocols.insert( const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second) return; for (auto *Proto : OP->protocols()) CollectInheritedProtocols(Proto, Protocols); } } static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD) { assert(RD->isUnion() && "Must be union type"); CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl()); for (const auto *Field : RD->fields()) { if (!Context.hasUniqueObjectRepresentations(Field->getType())) return false; CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType()); if (FieldSize != UnionSize) return false; } return !RD->field_empty(); } static bool isStructEmpty(QualType Ty) { const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl(); if (!RD->field_empty()) return false; if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) return ClassDecl->isEmpty(); return true; } static llvm::Optional<int64_t> structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD) { assert(!RD->isUnion() && "Must be struct/class type"); const auto &Layout = Context.getASTRecordLayout(RD); int64_t CurOffsetInBits = 0; if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) { if (ClassDecl->isDynamicClass()) return llvm::None; SmallVector<std::pair<QualType, int64_t>, 4> Bases; for (const auto &Base : ClassDecl->bases()) { // Empty types can be inherited from, and non-empty types can potentially // have tail padding, so just make sure there isn't an error. if (!isStructEmpty(Base.getType())) { llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations( Context, Base.getType()->castAs<RecordType>()->getDecl()); if (!Size) return llvm::None; Bases.emplace_back(Base.getType(), Size.getValue()); } } llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L, const std::pair<QualType, int64_t> &R) { return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) < Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl()); }); for (const auto &Base : Bases) { int64_t BaseOffset = Context.toBits( Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl())); int64_t BaseSize = Base.second; if (BaseOffset != CurOffsetInBits) return llvm::None; CurOffsetInBits = BaseOffset + BaseSize; } } for (const auto *Field : RD->fields()) { if (!Field->getType()->isReferenceType() && !Context.hasUniqueObjectRepresentations(Field->getType())) return llvm::None; int64_t FieldSizeInBits = Context.toBits(Context.getTypeSizeInChars(Field->getType())); if (Field->isBitField()) { int64_t BitfieldSize = Field->getBitWidthValue(Context); if (BitfieldSize > FieldSizeInBits) return llvm::None; FieldSizeInBits = BitfieldSize; } int64_t FieldOffsetInBits = Context.getFieldOffset(Field); if (FieldOffsetInBits != CurOffsetInBits) return llvm::None; CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits; } return CurOffsetInBits; } bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const { // C++17 [meta.unary.prop]: // The predicate condition for a template specialization // has_unique_object_representations<T> shall be // satisfied if and only if: // (9.1) - T is trivially copyable, and // (9.2) - any two objects of type T with the same value have the same // object representation, where two objects // of array or non-union class type are considered to have the same value // if their respective sequences of // direct subobjects have the same values, and two objects of union type // are considered to have the same // value if they have the same active member and the corresponding members // have the same value. // The set of scalar types for which this condition holds is // implementation-defined. [ Note: If a type has padding // bits, the condition does not hold; otherwise, the condition holds true // for unsigned integral types. -- end note ] assert(!Ty.isNull() && "Null QualType sent to unique object rep check"); // Arrays are unique only if their element type is unique. if (Ty->isArrayType()) return hasUniqueObjectRepresentations(getBaseElementType(Ty)); // (9.1) - T is trivially copyable... if (!Ty.isTriviallyCopyableType(*this)) return false; // All integrals and enums are unique. if (Ty->isIntegralOrEnumerationType()) return true; // All other pointers are unique. if (Ty->isPointerType()) return true; if (Ty->isMemberPointerType()) { const auto *MPT = Ty->getAs<MemberPointerType>(); return !ABI->getMemberPointerInfo(MPT).HasPadding; } if (Ty->isRecordType()) { const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl(); if (Record->isInvalidDecl()) return false; if (Record->isUnion()) return unionHasUniqueObjectRepresentations(*this, Record); Optional<int64_t> StructSize = structHasUniqueObjectRepresentations(*this, Record); return StructSize && StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty)); } // FIXME: More cases to handle here (list by rsmith): // vectors (careful about, eg, vector of 3 foo) // _Complex int and friends // _Atomic T // Obj-C block pointers // Obj-C object pointers // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t, // clk_event_t, queue_t, reserve_id_t) // There're also Obj-C class types and the Obj-C selector type, but I think it // makes sense for those to return false here. return false; } unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { unsigned count = 0; // Count ivars declared in class extension. for (const auto *Ext : OI->known_extensions()) count += Ext->ivar_size(); // Count ivar defined in this class's implementation. This // includes synthesized ivars. if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) count += ImplDecl->ivar_size(); return count; } bool ASTContext::isSentinelNullExpr(const Expr *E) { if (!E) return false; // nullptr_t is always treated as null. if (E->getType()->isNullPtrType()) return true; if (E->getType()->isAnyPointerType() && E->IgnoreParenCasts()->isNullPointerConstant(*this, Expr::NPC_ValueDependentIsNull)) return true; // Unfortunately, __null has type 'int'. if (isa<GNUNullExpr>(E)) return true; return false; } /// Get the implementation of ObjCInterfaceDecl, or nullptr if none /// exists. ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator I = ObjCImpls.find(D); if (I != ObjCImpls.end()) return cast<ObjCImplementationDecl>(I->second); return nullptr; } /// Get the implementation of ObjCCategoryDecl, or nullptr if none /// exists. ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator I = ObjCImpls.find(D); if (I != ObjCImpls.end()) return cast<ObjCCategoryImplDecl>(I->second); return nullptr; } /// Set the implementation of ObjCInterfaceDecl. void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, ObjCImplementationDecl *ImplD) { assert(IFaceD && ImplD && "Passed null params"); ObjCImpls[IFaceD] = ImplD; } /// Set the implementation of ObjCCategoryDecl. void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, ObjCCategoryImplDecl *ImplD) { assert(CatD && ImplD && "Passed null params"); ObjCImpls[CatD] = ImplD; } const ObjCMethodDecl * ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const { return ObjCMethodRedecls.lookup(MD); } void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl) { assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"); ObjCMethodRedecls[MD] = Redecl; } const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( const NamedDecl *ND) const { if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) return ID; if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) return CD->getClassInterface(); if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) return IMD->getClassInterface(); return nullptr; } /// Get the copy initialization expression of VarDecl, or nullptr if /// none exists. BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const { assert(VD && "Passed null params"); assert(VD->hasAttr<BlocksAttr>() && "getBlockVarCopyInits - not __block var"); auto I = BlockVarCopyInits.find(VD); if (I != BlockVarCopyInits.end()) return I->second; return {nullptr, false}; } /// Set the copy initialization expression of a block var decl. void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr, bool CanThrow) { assert(VD && CopyExpr && "Passed null params"); assert(VD->hasAttr<BlocksAttr>() && "setBlockVarCopyInits - not __block var"); BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow); } TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, unsigned DataSize) const { if (!DataSize) DataSize = TypeLoc::getFullDataSizeForType(T); else assert(DataSize == TypeLoc::getFullDataSizeForType(T) && "incorrect data size provided to CreateTypeSourceInfo!"); auto *TInfo = (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); new (TInfo) TypeSourceInfo(T); return TInfo; } TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, SourceLocation L) const { TypeSourceInfo *DI = CreateTypeSourceInfo(T); DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); return DI; } const ASTRecordLayout & ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { return getObjCLayout(D, nullptr); } const ASTRecordLayout & ASTContext::getASTObjCImplementationLayout( const ObjCImplementationDecl *D) const { return getObjCLayout(D->getClassInterface(), D); } //===----------------------------------------------------------------------===// // Type creation/memoization methods //===----------------------------------------------------------------------===// QualType ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { unsigned fastQuals = quals.getFastQualifiers(); quals.removeFastQualifiers(); // Check if we've already instantiated this type. llvm::FoldingSetNodeID ID; ExtQuals::Profile(ID, baseType, quals); void *insertPos = nullptr; if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { assert(eq->getQualifiers() == quals); return QualType(eq, fastQuals); } // If the base type is not canonical, make the appropriate canonical type. QualType canon; if (!baseType->isCanonicalUnqualified()) { SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); canonSplit.Quals.addConsistentQualifiers(quals); canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); // Re-find the insert position. (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); } auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); ExtQualNodes.InsertNode(eq, insertPos); return QualType(eq, fastQuals); } QualType ASTContext::getAddrSpaceQualType(QualType T, LangAS AddressSpace) const { QualType CanT = getCanonicalType(T); if (CanT.getAddressSpace() == AddressSpace) return T; // If we are composing extended qualifiers together, merge together // into one ExtQuals node. QualifierCollector Quals; const Type *TypeNode = Quals.strip(T); // If this type already has an address space specified, it cannot get // another one. assert(!Quals.hasAddressSpace() && "Type cannot be in multiple addr spaces!"); Quals.addAddressSpace(AddressSpace); return getExtQualType(TypeNode, Quals); } QualType ASTContext::removeAddrSpaceQualType(QualType T) const { // If we are composing extended qualifiers together, merge together // into one ExtQuals node. QualifierCollector Quals; const Type *TypeNode = Quals.strip(T); // If the qualifier doesn't have an address space just return it. if (!Quals.hasAddressSpace()) return T; Quals.removeAddressSpace(); // Removal of the address space can mean there are no longer any // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts) // or required. if (Quals.hasNonFastQualifiers()) return getExtQualType(TypeNode, Quals); else return QualType(TypeNode, Quals.getFastQualifiers()); } QualType ASTContext::getObjCGCQualType(QualType T, Qualifiers::GC GCAttr) const { QualType CanT = getCanonicalType(T); if (CanT.getObjCGCAttr() == GCAttr) return T; if (const auto *ptr = T->getAs<PointerType>()) { QualType Pointee = ptr->getPointeeType(); if (Pointee->isAnyPointerType()) { QualType ResultType = getObjCGCQualType(Pointee, GCAttr); return getPointerType(ResultType); } } // If we are composing extended qualifiers together, merge together // into one ExtQuals node. QualifierCollector Quals; const Type *TypeNode = Quals.strip(T); // If this type already has an ObjCGC specified, it cannot get // another one. assert(!Quals.hasObjCGCAttr() && "Type cannot have multiple ObjCGCs!"); Quals.addObjCGCAttr(GCAttr); return getExtQualType(TypeNode, Quals); } QualType ASTContext::removePtrSizeAddrSpace(QualType T) const { if (const PointerType *Ptr = T->getAs<PointerType>()) { QualType Pointee = Ptr->getPointeeType(); if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) { return getPointerType(removeAddrSpaceQualType(Pointee)); } } return T; } const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, FunctionType::ExtInfo Info) { if (T->getExtInfo() == Info) return T; QualType Result; if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) { Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); } else { const auto *FPT = cast<FunctionProtoType>(T); FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); EPI.ExtInfo = Info; Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); } return cast<FunctionType>(Result.getTypePtr()); } void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType) { FD = FD->getMostRecentDecl(); while (true) { const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); if (FunctionDecl *Next = FD->getPreviousDecl()) FD = Next; else break; } if (ASTMutationListener *L = getASTMutationListener()) L->DeducedReturnType(FD, ResultType); } /// Get a function type and produce the equivalent function type with the /// specified exception specification. Type sugar that can be present on a /// declaration of a function with an exception specification is permitted /// and preserved. Other type sugar (for instance, typedefs) is not. QualType ASTContext::getFunctionTypeWithExceptionSpec( QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) { // Might have some parens. if (const auto *PT = dyn_cast<ParenType>(Orig)) return getParenType( getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI)); // Might be wrapped in a macro qualified type. if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig)) return getMacroQualifiedType( getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI), MQT->getMacroIdentifier()); // Might have a calling-convention attribute. if (const auto *AT = dyn_cast<AttributedType>(Orig)) return getAttributedType( AT->getAttrKind(), getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI), getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI)); // Anything else must be a function type. Rebuild it with the new exception // specification. const auto *Proto = Orig->castAs<FunctionProtoType>(); return getFunctionType( Proto->getReturnType(), Proto->getParamTypes(), Proto->getExtProtoInfo().withExceptionSpec(ESI)); } bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) { return hasSameType(T, U) || (getLangOpts().CPlusPlus17 && hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None), getFunctionTypeWithExceptionSpec(U, EST_None))); } QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) { if (const auto *Proto = T->getAs<FunctionProtoType>()) { QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); SmallVector<QualType, 16> Args(Proto->param_types()); for (unsigned i = 0, n = Args.size(); i != n; ++i) Args[i] = removePtrSizeAddrSpace(Args[i]); return getFunctionType(RetTy, Args, Proto->getExtProtoInfo()); } if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) { QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); return getFunctionNoProtoType(RetTy, Proto->getExtInfo()); } return T; } bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) { return hasSameType(T, U) || hasSameType(getFunctionTypeWithoutPtrSizes(T), getFunctionTypeWithoutPtrSizes(U)); } void ASTContext::adjustExceptionSpec( FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten) { // Update the type. QualType Updated = getFunctionTypeWithExceptionSpec(FD->getType(), ESI); FD->setType(Updated); if (!AsWritten) return; // Update the type in the type source information too. if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { // If the type and the type-as-written differ, we may need to update // the type-as-written too. if (TSInfo->getType() != FD->getType()) Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI); // FIXME: When we get proper type location information for exceptions, // we'll also have to rebuild the TypeSourceInfo. For now, we just patch // up the TypeSourceInfo; assert(TypeLoc::getFullDataSizeForType(Updated) == TypeLoc::getFullDataSizeForType(TSInfo->getType()) && "TypeLoc size mismatch from updating exception specification"); TSInfo->overrideType(Updated); } } /// getComplexType - Return the uniqued reference to the type for a complex /// number with the specified element type. QualType ASTContext::getComplexType(QualType T) const { // Unique pointers, to guarantee there is only one pointer of a particular // structure. llvm::FoldingSetNodeID ID; ComplexType::Profile(ID, T); void *InsertPos = nullptr; if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(CT, 0); // If the pointee type isn't canonical, this won't be a canonical type either, // so fill in the canonical type field. QualType Canonical; if (!T.isCanonical()) { Canonical = getComplexType(getCanonicalType(T)); // Get the new insert position for the node we care about. ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; } auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical); Types.push_back(New); ComplexTypes.InsertNode(New, InsertPos); return QualType(New, 0); } /// getPointerType - Return the uniqued reference to the type for a pointer to /// the specified type. QualType ASTContext::getPointerType(QualType T) const { // Unique pointers, to guarantee there is only one pointer of a particular // structure. llvm::FoldingSetNodeID ID; PointerType::Profile(ID, T); void *InsertPos = nullptr; if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(PT, 0); // If the pointee type isn't canonical, this won't be a canonical type either, // so fill in the canonical type field. QualType Canonical; if (!T.isCanonical()) { Canonical = getPointerType(getCanonicalType(T)); // Get the new insert position for the node we care about. PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; } auto *New = new (*this, TypeAlignment) PointerType(T, Canonical); Types.push_back(New); PointerTypes.InsertNode(New, InsertPos); return QualType(New, 0); } QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { llvm::FoldingSetNodeID ID; AdjustedType::Profile(ID, Orig, New); void *InsertPos = nullptr; AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); if (AT) return QualType(AT, 0); QualType Canonical = getCanonicalType(New); // Get the new insert position for the node we care about. AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!AT && "Shouldn't be in the map!"); AT = new (*this, TypeAlignment) AdjustedType(Type::Adjusted, Orig, New, Canonical); Types.push_back(AT); AdjustedTypes.InsertNode(AT, InsertPos); return QualType(AT, 0); } QualType ASTContext::getDecayedType(QualType T) const { assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); QualType Decayed; // C99 6.7.5.3p7: // A declaration of a parameter as "array of type" shall be // adjusted to "qualified pointer to type", where the type // qualifiers (if any) are those specified within the [ and ] of // the array type derivation. if (T->isArrayType()) Decayed = getArrayDecayedType(T); // C99 6.7.5.3p8: // A declaration of a parameter as "function returning type" // shall be adjusted to "pointer to function returning type", as // in 6.3.2.1. if (T->isFunctionType()) Decayed = getPointerType(T); llvm::FoldingSetNodeID ID; AdjustedType::Profile(ID, T, Decayed); void *InsertPos = nullptr; AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); if (AT) return QualType(AT, 0); QualType Canonical = getCanonicalType(Decayed); // Get the new insert position for the node we care about. AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!AT && "Shouldn't be in the map!"); AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); Types.push_back(AT); AdjustedTypes.InsertNode(AT, InsertPos); return QualType(AT, 0); } /// getBlockPointerType - Return the uniqued reference to the type for /// a pointer to the specified block. QualType ASTContext::getBlockPointerType(QualType T) const { assert(T->isFunctionType() && "block of function types only"); // Unique pointers, to guarantee there is only one block of a particular // structure. llvm::FoldingSetNodeID ID; BlockPointerType::Profile(ID, T); void *InsertPos = nullptr; if (BlockPointerType *PT = BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(PT, 0); // If the block pointee type isn't canonical, this won't be a canonical // type either so fill in the canonical type field. QualType Canonical; if (!T.isCanonical()) { Canonical = getBlockPointerType(getCanonicalType(T)); // Get the new insert position for the node we care about. BlockPointerType *NewIP = BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; } auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical); Types.push_back(New); BlockPointerTypes.InsertNode(New, InsertPos); return QualType(New, 0); } /// getLValueReferenceType - Return the uniqued reference to the type for an /// lvalue reference to the specified type. QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { assert(getCanonicalType(T) != OverloadTy && "Unresolved overloaded function type"); // Unique pointers, to guarantee there is only one pointer of a particular // structure. llvm::FoldingSetNodeID ID; ReferenceType::Profile(ID, T, SpelledAsLValue); void *InsertPos = nullptr; if (LValueReferenceType *RT = LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(RT, 0); const auto *InnerRef = T->getAs<ReferenceType>(); // If the referencee type isn't canonical, this won't be a canonical type // either, so fill in the canonical type field. QualType Canonical; if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); // Get the new insert position for the node we care about. LValueReferenceType *NewIP = LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; } auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, SpelledAsLValue); Types.push_back(New); LValueReferenceTypes.InsertNode(New, InsertPos); return QualType(New, 0); } /// getRValueReferenceType - Return the uniqued reference to the type for an /// rvalue reference to the specified type. QualType ASTContext::getRValueReferenceType(QualType T) const { // Unique pointers, to guarantee there is only one pointer of a particular // structure. llvm::FoldingSetNodeID ID; ReferenceType::Profile(ID, T, false); void *InsertPos = nullptr; if (RValueReferenceType *RT = RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(RT, 0); const auto *InnerRef = T->getAs<ReferenceType>(); // If the referencee type isn't canonical, this won't be a canonical type // either, so fill in the canonical type field. QualType Canonical; if (InnerRef || !T.isCanonical()) { QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); // Get the new insert position for the node we care about. RValueReferenceType *NewIP = RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; } auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); Types.push_back(New); RValueReferenceTypes.InsertNode(New, InsertPos); return QualType(New, 0); } /// getMemberPointerType - Return the uniqued reference to the type for a /// member pointer to the specified type, in the specified class. QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { // Unique pointers, to guarantee there is only one pointer of a particular // structure. llvm::FoldingSetNodeID ID; MemberPointerType::Profile(ID, T, Cls); void *InsertPos = nullptr; if (MemberPointerType *PT = MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(PT, 0); // If the pointee or class type isn't canonical, this won't be a canonical // type either, so fill in the canonical type field. QualType Canonical; if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); // Get the new insert position for the node we care about. MemberPointerType *NewIP = MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; } auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); Types.push_back(New); MemberPointerTypes.InsertNode(New, InsertPos); return QualType(New, 0); } /// getConstantArrayType - Return the unique reference to the type for an /// array of the specified element type. QualType ASTContext::getConstantArrayType(QualType EltTy, const llvm::APInt &ArySizeIn, const Expr *SizeExpr, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const { assert((EltTy->isDependentType() || EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && "Constant array of VLAs is illegal!"); // We only need the size as part of the type if it's instantiation-dependent. if (SizeExpr && !SizeExpr->isInstantiationDependent()) SizeExpr = nullptr; // Convert the array size into a canonical width matching the pointer size for // the target. llvm::APInt ArySize(ArySizeIn); ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth()); llvm::FoldingSetNodeID ID; ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM, IndexTypeQuals); void *InsertPos = nullptr; if (ConstantArrayType *ATP = ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(ATP, 0); // If the element type isn't canonical or has qualifiers, or the array bound // is instantiation-dependent, this won't be a canonical type either, so fill // in the canonical type field. QualType Canon; if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) { SplitQualType canonSplit = getCanonicalType(EltTy).split(); Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr, ASM, IndexTypeQuals); Canon = getQualifiedType(Canon, canonSplit.Quals); // Get the new insert position for the node we care about. ConstantArrayType *NewIP = ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; } void *Mem = Allocate( ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0), TypeAlignment); auto *New = new (Mem) ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals); ConstantArrayTypes.InsertNode(New, InsertPos); Types.push_back(New); return QualType(New, 0); } /// getVariableArrayDecayedType - Turns the given type, which may be /// variably-modified, into the corresponding type with all the known /// sizes replaced with [*]. QualType ASTContext::getVariableArrayDecayedType(QualType type) const { // Vastly most common case. if (!type->isVariablyModifiedType()) return type; QualType result; SplitQualType split = type.getSplitDesugaredType(); const Type *ty = split.Ty; switch (ty->getTypeClass()) { #define TYPE(Class, Base) #define ABSTRACT_TYPE(Class, Base) #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: #include "clang/AST/TypeNodes.inc" llvm_unreachable("didn't desugar past all non-canonical types?"); // These types should never be variably-modified. case Type::Builtin: case Type::Complex: case Type::Vector: case Type::DependentVector: case Type::ExtVector: case Type::DependentSizedExtVector: case Type::DependentAddressSpace: case Type::ObjCObject: case Type::ObjCInterface: case Type::ObjCObjectPointer: case Type::Record: case Type::Enum: case Type::UnresolvedUsing: case Type::TypeOfExpr: case Type::TypeOf: case Type::Decltype: case Type::UnaryTransform: case Type::DependentName: case Type::InjectedClassName: case Type::TemplateSpecialization: case Type::DependentTemplateSpecialization: case Type::TemplateTypeParm: case Type::SubstTemplateTypeParmPack: case Type::Auto: case Type::DeducedTemplateSpecialization: case Type::PackExpansion: llvm_unreachable("type should never be variably-modified"); // These types can be variably-modified but should never need to // further decay. case Type::FunctionNoProto: case Type::FunctionProto: case Type::BlockPointer: case Type::MemberPointer: case Type::Pipe: return type; // These types can be variably-modified. All these modifications // preserve structure except as noted by comments. // TODO: if we ever care about optimizing VLAs, there are no-op // optimizations available here. case Type::Pointer: result = getPointerType(getVariableArrayDecayedType( cast<PointerType>(ty)->getPointeeType())); break; case Type::LValueReference: { const auto *lv = cast<LValueReferenceType>(ty); result = getLValueReferenceType( getVariableArrayDecayedType(lv->getPointeeType()), lv->isSpelledAsLValue()); break; } case Type::RValueReference: { const auto *lv = cast<RValueReferenceType>(ty); result = getRValueReferenceType( getVariableArrayDecayedType(lv->getPointeeType())); break; } case Type::Atomic: { const auto *at = cast<AtomicType>(ty); result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); break; } case Type::ConstantArray: { const auto *cat = cast<ConstantArrayType>(ty); result = getConstantArrayType( getVariableArrayDecayedType(cat->getElementType()), cat->getSize(), cat->getSizeExpr(), cat->getSizeModifier(), cat->getIndexTypeCVRQualifiers()); break; } case Type::DependentSizedArray: { const auto *dat = cast<DependentSizedArrayType>(ty); result = getDependentSizedArrayType( getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(), dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers(), dat->getBracketsRange()); break; } // Turn incomplete types into [*] types. case Type::IncompleteArray: { const auto *iat = cast<IncompleteArrayType>(ty); result = getVariableArrayType( getVariableArrayDecayedType(iat->getElementType()), /*size*/ nullptr, ArrayType::Normal, iat->getIndexTypeCVRQualifiers(), SourceRange()); break; } // Turn VLA types into [*] types. case Type::VariableArray: { const auto *vat = cast<VariableArrayType>(ty); result = getVariableArrayType( getVariableArrayDecayedType(vat->getElementType()), /*size*/ nullptr, ArrayType::Star, vat->getIndexTypeCVRQualifiers(), vat->getBracketsRange()); break; } } // Apply the top-level qualifiers from the original. return getQualifiedType(result, split.Quals); } /// getVariableArrayType - Returns a non-unique reference to the type for a /// variable array of the specified element type. QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const { // Since we don't unique expressions, it isn't possible to unique VLA's // that have an expression provided for their size. QualType Canon; // Be sure to pull qualifiers off the element type. if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { SplitQualType canonSplit = getCanonicalType(EltTy).split(); Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, IndexTypeQuals, Brackets); Canon = getQualifiedType(Canon, canonSplit.Quals); } auto *New = new (*this, TypeAlignment) VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); VariableArrayTypes.push_back(New); Types.push_back(New); return QualType(New, 0); } /// getDependentSizedArrayType - Returns a non-unique reference to /// the type for a dependently-sized array of the specified element /// type. QualType ASTContext::getDependentSizedArrayType(QualType elementType, Expr *numElements, ArrayType::ArraySizeModifier ASM, unsigned elementTypeQuals, SourceRange brackets) const { assert((!numElements || numElements->isTypeDependent() || numElements->isValueDependent()) && "Size must be type- or value-dependent!"); // Dependently-sized array types that do not have a specified number // of elements will have their sizes deduced from a dependent // initializer. We do no canonicalization here at all, which is okay // because they can't be used in most locations. if (!numElements) { auto *newType = new (*this, TypeAlignment) DependentSizedArrayType(*this, elementType, QualType(), numElements, ASM, elementTypeQuals, brackets); Types.push_back(newType); return QualType(newType, 0); } // Otherwise, we actually build a new type every time, but we // also build a canonical type. SplitQualType canonElementType = getCanonicalType(elementType).split(); void *insertPos = nullptr; llvm::FoldingSetNodeID ID; DependentSizedArrayType::Profile(ID, *this, QualType(canonElementType.Ty, 0), ASM, elementTypeQuals, numElements); // Look for an existing type with these properties. DependentSizedArrayType *canonTy = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); // If we don't have one, build one. if (!canonTy) { canonTy = new (*this, TypeAlignment) DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), QualType(), numElements, ASM, elementTypeQuals, brackets); DependentSizedArrayTypes.InsertNode(canonTy, insertPos); Types.push_back(canonTy); } // Apply qualifiers from the element type to the array. QualType canon = getQualifiedType(QualType(canonTy,0), canonElementType.Quals); // If we didn't need extra canonicalization for the element type or the size // expression, then just use that as our result. if (QualType(canonElementType.Ty, 0) == elementType && canonTy->getSizeExpr() == numElements) return canon; // Otherwise, we need to build a type which follows the spelling // of the element type. auto *sugaredType = new (*this, TypeAlignment) DependentSizedArrayType(*this, elementType, canon, numElements, ASM, elementTypeQuals, brackets); Types.push_back(sugaredType); return QualType(sugaredType, 0); } QualType ASTContext::getIncompleteArrayType(QualType elementType, ArrayType::ArraySizeModifier ASM, unsigned elementTypeQuals) const { llvm::FoldingSetNodeID ID; IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); void *insertPos = nullptr; if (IncompleteArrayType *iat = IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) return QualType(iat, 0); // If the element type isn't canonical, this won't be a canonical type // either, so fill in the canonical type field. We also have to pull // qualifiers off the element type. QualType canon; if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { SplitQualType canonSplit = getCanonicalType(elementType).split(); canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), ASM, elementTypeQuals); canon = getQualifiedType(canon, canonSplit.Quals); // Get the new insert position for the node we care about. IncompleteArrayType *existing = IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); assert(!existing && "Shouldn't be in the map!"); (void) existing; } auto *newType = new (*this, TypeAlignment) IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); IncompleteArrayTypes.InsertNode(newType, insertPos); Types.push_back(newType); return QualType(newType, 0); } /// getVectorType - Return the unique reference to a vector type of /// the specified element type and size. VectorType must be a built-in type. QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, VectorType::VectorKind VecKind) const { assert(vecType->isBuiltinType()); // Check if we've already instantiated a vector of this type. llvm::FoldingSetNodeID ID; VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); void *InsertPos = nullptr; if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(VTP, 0); // If the element type isn't canonical, this won't be a canonical type either, // so fill in the canonical type field. QualType Canonical; if (!vecType.isCanonical()) { Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); // Get the new insert position for the node we care about. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; } auto *New = new (*this, TypeAlignment) VectorType(vecType, NumElts, Canonical, VecKind); VectorTypes.InsertNode(New, InsertPos); Types.push_back(New); return QualType(New, 0); } QualType ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr, SourceLocation AttrLoc, VectorType::VectorKind VecKind) const { llvm::FoldingSetNodeID ID; DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr, VecKind); void *InsertPos = nullptr; DependentVectorType *Canon = DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); DependentVectorType *New; if (Canon) { New = new (*this, TypeAlignment) DependentVectorType( *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind); } else { QualType CanonVecTy = getCanonicalType(VecType); if (CanonVecTy == VecType) { New = new (*this, TypeAlignment) DependentVectorType( *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind); DependentVectorType *CanonCheck = DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!CanonCheck && "Dependent-sized vector_size canonical type broken"); (void)CanonCheck; DependentVectorTypes.InsertNode(New, InsertPos); } else { QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, SourceLocation()); New = new (*this, TypeAlignment) DependentVectorType( *this, VecType, CanonExtTy, SizeExpr, AttrLoc, VecKind); } } Types.push_back(New); return QualType(New, 0); } /// getExtVectorType - Return the unique reference to an extended vector type of /// the specified element type and size. VectorType must be a built-in type. QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { assert(vecType->isBuiltinType() || vecType->isDependentType()); // Check if we've already instantiated a vector of this type. llvm::FoldingSetNodeID ID; VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, VectorType::GenericVector); void *InsertPos = nullptr; if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(VTP, 0); // If the element type isn't canonical, this won't be a canonical type either, // so fill in the canonical type field. QualType Canonical; if (!vecType.isCanonical()) { Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); // Get the new insert position for the node we care about. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; } auto *New = new (*this, TypeAlignment) ExtVectorType(vecType, NumElts, Canonical); VectorTypes.InsertNode(New, InsertPos); Types.push_back(New); return QualType(New, 0); } QualType ASTContext::getDependentSizedExtVectorType(QualType vecType, Expr *SizeExpr, SourceLocation AttrLoc) const { llvm::FoldingSetNodeID ID; DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), SizeExpr); void *InsertPos = nullptr; DependentSizedExtVectorType *Canon = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); DependentSizedExtVectorType *New; if (Canon) { // We already have a canonical version of this array type; use it as // the canonical type for a newly-built type. New = new (*this, TypeAlignment) DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), SizeExpr, AttrLoc); } else { QualType CanonVecTy = getCanonicalType(vecType); if (CanonVecTy == vecType) { New = new (*this, TypeAlignment) DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, AttrLoc); DependentSizedExtVectorType *CanonCheck = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); (void)CanonCheck; DependentSizedExtVectorTypes.InsertNode(New, InsertPos); } else { QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, SourceLocation()); New = new (*this, TypeAlignment) DependentSizedExtVectorType( *this, vecType, CanonExtTy, SizeExpr, AttrLoc); } } Types.push_back(New); return QualType(New, 0); } QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const { assert(AddrSpaceExpr->isInstantiationDependent()); QualType canonPointeeType = getCanonicalType(PointeeType); void *insertPos = nullptr; llvm::FoldingSetNodeID ID; DependentAddressSpaceType::Profile(ID, *this, canonPointeeType, AddrSpaceExpr); DependentAddressSpaceType *canonTy = DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos); if (!canonTy) { canonTy = new (*this, TypeAlignment) DependentAddressSpaceType(*this, canonPointeeType, QualType(), AddrSpaceExpr, AttrLoc); DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); Types.push_back(canonTy); } if (canonPointeeType == PointeeType && canonTy->getAddrSpaceExpr() == AddrSpaceExpr) return QualType(canonTy, 0); auto *sugaredType = new (*this, TypeAlignment) DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), AddrSpaceExpr, AttrLoc); Types.push_back(sugaredType); return QualType(sugaredType, 0); } /// Determine whether \p T is canonical as the result type of a function. static bool isCanonicalResultType(QualType T) { return T.isCanonical() && (T.getObjCLifetime() == Qualifiers::OCL_None || T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); } /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const { // Unique functions, to guarantee there is only one function of a particular // structure. llvm::FoldingSetNodeID ID; FunctionNoProtoType::Profile(ID, ResultTy, Info); void *InsertPos = nullptr; if (FunctionNoProtoType *FT = FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(FT, 0); QualType Canonical; if (!isCanonicalResultType(ResultTy)) { Canonical = getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); // Get the new insert position for the node we care about. FunctionNoProtoType *NewIP = FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; } auto *New = new (*this, TypeAlignment) FunctionNoProtoType(ResultTy, Canonical, Info); Types.push_back(New); FunctionNoProtoTypes.InsertNode(New, InsertPos); return QualType(New, 0); } CanQualType ASTContext::getCanonicalFunctionResultType(QualType ResultType) const { CanQualType CanResultType = getCanonicalType(ResultType); // Canonical result types do not have ARC lifetime qualifiers. if (CanResultType.getQualifiers().hasObjCLifetime()) { Qualifiers Qs = CanResultType.getQualifiers(); Qs.removeObjCLifetime(); return CanQualType::CreateUnsafe( getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); } return CanResultType; } static bool isCanonicalExceptionSpecification( const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) { if (ESI.Type == EST_None) return true; if (!NoexceptInType) return false; // C++17 onwards: exception specification is part of the type, as a simple // boolean "can this function type throw". if (ESI.Type == EST_BasicNoexcept) return true; // A noexcept(expr) specification is (possibly) canonical if expr is // value-dependent. if (ESI.Type == EST_DependentNoexcept) return true; // A dynamic exception specification is canonical if it only contains pack // expansions (so we can't tell whether it's non-throwing) and all its // contained types are canonical. if (ESI.Type == EST_Dynamic) { bool AnyPackExpansions = false; for (QualType ET : ESI.Exceptions) { if (!ET.isCanonical()) return false; if (ET->getAs<PackExpansionType>()) AnyPackExpansions = true; } return AnyPackExpansions; } return false; } QualType ASTContext::getFunctionTypeInternal( QualType ResultTy, ArrayRef<QualType> ArgArray, const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const { size_t NumArgs = ArgArray.size(); // Unique functions, to guarantee there is only one function of a particular // structure. llvm::FoldingSetNodeID ID; FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, *this, true); QualType Canonical; bool Unique = false; void *InsertPos = nullptr; if (FunctionProtoType *FPT = FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) { QualType Existing = QualType(FPT, 0); // If we find a pre-existing equivalent FunctionProtoType, we can just reuse // it so long as our exception specification doesn't contain a dependent // noexcept expression, or we're just looking for a canonical type. // Otherwise, we're going to need to create a type // sugar node to hold the concrete expression. if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) || EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr()) return Existing; // We need a new type sugar node for this one, to hold the new noexcept // expression. We do no canonicalization here, but that's OK since we don't // expect to see the same noexcept expression much more than once. Canonical = getCanonicalType(Existing); Unique = true; } bool NoexceptInType = getLangOpts().CPlusPlus17; bool IsCanonicalExceptionSpec = isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType); // Determine whether the type being created is already canonical or not. bool isCanonical = !Unique && IsCanonicalExceptionSpec && isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn; for (unsigned i = 0; i != NumArgs && isCanonical; ++i) if (!ArgArray[i].isCanonicalAsParam()) isCanonical = false; if (OnlyWantCanonical) assert(isCanonical && "given non-canonical parameters constructing canonical type"); // If this type isn't canonical, get the canonical version of it if we don't // already have it. The exception spec is only partially part of the // canonical type, and only in C++17 onwards. if (!isCanonical && Canonical.isNull()) { SmallVector<QualType, 16> CanonicalArgs; CanonicalArgs.reserve(NumArgs); for (unsigned i = 0; i != NumArgs; ++i) CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); llvm::SmallVector<QualType, 8> ExceptionTypeStorage; FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; CanonicalEPI.HasTrailingReturn = false; if (IsCanonicalExceptionSpec) { // Exception spec is already OK. } else if (NoexceptInType) { switch (EPI.ExceptionSpec.Type) { case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated: // We don't know yet. It shouldn't matter what we pick here; no-one // should ever look at this. LLVM_FALLTHROUGH; case EST_None: case EST_MSAny: case EST_NoexceptFalse: CanonicalEPI.ExceptionSpec.Type = EST_None; break; // A dynamic exception specification is almost always "not noexcept", // with the exception that a pack expansion might expand to no types. case EST_Dynamic: { bool AnyPacks = false; for (QualType ET : EPI.ExceptionSpec.Exceptions) { if (ET->getAs<PackExpansionType>()) AnyPacks = true; ExceptionTypeStorage.push_back(getCanonicalType(ET)); } if (!AnyPacks) CanonicalEPI.ExceptionSpec.Type = EST_None; else { CanonicalEPI.ExceptionSpec.Type = EST_Dynamic; CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage; } break; } case EST_DynamicNone: case EST_BasicNoexcept: case EST_NoexceptTrue: case EST_NoThrow: CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept; break; case EST_DependentNoexcept: llvm_unreachable("dependent noexcept is already canonical"); } } else { CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); } // Adjust the canonical function result type. CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy); Canonical = getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true); // Get the new insert position for the node we care about. FunctionProtoType *NewIP = FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; } // Compute the needed size to hold this FunctionProtoType and the // various trailing objects. auto ESH = FunctionProtoType::getExceptionSpecSize( EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size()); size_t Size = FunctionProtoType::totalSizeToAlloc< QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType, Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers>( NumArgs, EPI.Variadic, FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type), ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr, EPI.ExtParameterInfos ? NumArgs : 0, EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0); auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment); FunctionProtoType::ExtProtoInfo newEPI = EPI; new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); Types.push_back(FTP); if (!Unique) FunctionProtoTypes.InsertNode(FTP, InsertPos); return QualType(FTP, 0); } QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const { llvm::FoldingSetNodeID ID; PipeType::Profile(ID, T, ReadOnly); void *InsertPos = nullptr; if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(PT, 0); // If the pipe element type isn't canonical, this won't be a canonical type // either, so fill in the canonical type field. QualType Canonical; if (!T.isCanonical()) { Canonical = getPipeType(getCanonicalType(T), ReadOnly); // Get the new insert position for the node we care about. PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; } auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly); Types.push_back(New); PipeTypes.InsertNode(New, InsertPos); return QualType(New, 0); } QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const { // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant) : Ty; } QualType ASTContext::getReadPipeType(QualType T) const { return getPipeType(T, true); } QualType ASTContext::getWritePipeType(QualType T) const { return getPipeType(T, false); } #ifndef NDEBUG static bool NeedsInjectedClassNameType(const RecordDecl *D) { if (!isa<CXXRecordDecl>(D)) return false; const auto *RD = cast<CXXRecordDecl>(D); if (isa<ClassTemplatePartialSpecializationDecl>(RD)) return true; if (RD->getDescribedClassTemplate() && !isa<ClassTemplateSpecializationDecl>(RD)) return true; return false; } #endif /// getInjectedClassNameType - Return the unique reference to the /// injected class name type for the specified templated declaration. QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const { assert(NeedsInjectedClassNameType(Decl)); if (Decl->TypeForDecl) { assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { assert(PrevDecl->TypeForDecl && "previous declaration has no type"); Decl->TypeForDecl = PrevDecl->TypeForDecl; assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); } else { Type *newType = new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); Decl->TypeForDecl = newType; Types.push_back(newType); } return QualType(Decl->TypeForDecl, 0); } /// getTypeDeclType - Return the unique reference to the type for the /// specified type declaration. QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { assert(Decl && "Passed null for Decl param"); assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl)) return getTypedefType(Typedef); assert(!isa<TemplateTypeParmDecl>(Decl) && "Template type parameter types are always available."); if (const auto *Record = dyn_cast<RecordDecl>(Decl)) { assert(Record->isFirstDecl() && "struct/union has previous declaration"); assert(!NeedsInjectedClassNameType(Record)); return getRecordType(Record); } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) { assert(Enum->isFirstDecl() && "enum has previous declaration"); return getEnumType(Enum); } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); Decl->TypeForDecl = newType; Types.push_back(newType); } else llvm_unreachable("TypeDecl without a type?"); return QualType(Decl->TypeForDecl, 0); } /// getTypedefType - Return the unique reference to the type for the /// specified typedef name decl. QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl, QualType Canonical) const { if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); if (Canonical.isNull()) Canonical = getCanonicalType(Decl->getUnderlyingType()); auto *newType = new (*this, TypeAlignment) TypedefType(Type::Typedef, Decl, Canonical); Decl->TypeForDecl = newType; Types.push_back(newType); return QualType(newType, 0); } QualType ASTContext::getRecordType(const RecordDecl *Decl) const { if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) if (PrevDecl->TypeForDecl) return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); auto *newType = new (*this, TypeAlignment) RecordType(Decl); Decl->TypeForDecl = newType; Types.push_back(newType); return QualType(newType, 0); } QualType ASTContext::getEnumType(const EnumDecl *Decl) const { if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) if (PrevDecl->TypeForDecl) return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); auto *newType = new (*this, TypeAlignment) EnumType(Decl); Decl->TypeForDecl = newType; Types.push_back(newType); return QualType(newType, 0); } QualType ASTContext::getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) { llvm::FoldingSetNodeID id; AttributedType::Profile(id, attrKind, modifiedType, equivalentType); void *insertPos = nullptr; AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); if (type) return QualType(type, 0); QualType canon = getCanonicalType(equivalentType); type = new (*this, TypeAlignment) AttributedType(canon, attrKind, modifiedType, equivalentType); Types.push_back(type); AttributedTypes.InsertNode(type, insertPos); return QualType(type, 0); } /// Retrieve a substitution-result type. QualType ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, QualType Replacement) const { assert(Replacement.isCanonical() && "replacement types must always be canonical"); llvm::FoldingSetNodeID ID; SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); void *InsertPos = nullptr; SubstTemplateTypeParmType *SubstParm = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); if (!SubstParm) { SubstParm = new (*this, TypeAlignment) SubstTemplateTypeParmType(Parm, Replacement); Types.push_back(SubstParm); SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); } return QualType(SubstParm, 0); } /// Retrieve a QualType ASTContext::getSubstTemplateTypeParmPackType( const TemplateTypeParmType *Parm, const TemplateArgument &ArgPack) { #ifndef NDEBUG for (const auto &P : ArgPack.pack_elements()) { assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); } #endif llvm::FoldingSetNodeID ID; SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); void *InsertPos = nullptr; if (SubstTemplateTypeParmPackType *SubstParm = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(SubstParm, 0); QualType Canon; if (!Parm->isCanonicalUnqualified()) { Canon = getCanonicalType(QualType(Parm, 0)); Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), ArgPack); SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); } auto *SubstParm = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, ArgPack); Types.push_back(SubstParm); SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); return QualType(SubstParm, 0); } /// Retrieve the template type parameter type for a template /// parameter or parameter pack with the given depth, index, and (optionally) /// name. QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, TemplateTypeParmDecl *TTPDecl) const { llvm::FoldingSetNodeID ID; TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); void *InsertPos = nullptr; TemplateTypeParmType *TypeParm = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); if (TypeParm) return QualType(TypeParm, 0); if (TTPDecl) { QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); TemplateTypeParmType *TypeCheck = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!TypeCheck && "Template type parameter canonical type broken"); (void)TypeCheck; } else TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(Depth, Index, ParameterPack); Types.push_back(TypeParm); TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); return QualType(TypeParm, 0); } TypeSourceInfo * ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, SourceLocation NameLoc, const TemplateArgumentListInfo &Args, QualType Underlying) const { assert(!Name.getAsDependentTemplateName() && "No dependent template names here!"); QualType TST = getTemplateSpecializationType(Name, Args, Underlying); TypeSourceInfo *DI = CreateTypeSourceInfo(TST); TemplateSpecializationTypeLoc TL = DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); TL.setTemplateKeywordLoc(SourceLocation()); TL.setTemplateNameLoc(NameLoc); TL.setLAngleLoc(Args.getLAngleLoc()); TL.setRAngleLoc(Args.getRAngleLoc()); for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) TL.setArgLocInfo(i, Args[i].getLocInfo()); return DI; } QualType ASTContext::getTemplateSpecializationType(TemplateName Template, const TemplateArgumentListInfo &Args, QualType Underlying) const { assert(!Template.getAsDependentTemplateName() && "No dependent template names here!"); SmallVector<TemplateArgument, 4> ArgVec; ArgVec.reserve(Args.size()); for (const TemplateArgumentLoc &Arg : Args.arguments()) ArgVec.push_back(Arg.getArgument()); return getTemplateSpecializationType(Template, ArgVec, Underlying); } #ifndef NDEBUG static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { for (const TemplateArgument &Arg : Args) if (Arg.isPackExpansion()) return true; return true; } #endif QualType ASTContext::getTemplateSpecializationType(TemplateName Template, ArrayRef<TemplateArgument> Args, QualType Underlying) const { assert(!Template.getAsDependentTemplateName() && "No dependent template names here!"); // Look through qualified template names. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) Template = TemplateName(QTN->getTemplateDecl()); bool IsTypeAlias = Template.getAsTemplateDecl() && isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); QualType CanonType; if (!Underlying.isNull()) CanonType = getCanonicalType(Underlying); else { // We can get here with an alias template when the specialization contains // a pack expansion that does not match up with a parameter pack. assert((!IsTypeAlias || hasAnyPackExpansions(Args)) && "Caller must compute aliased type"); IsTypeAlias = false; CanonType = getCanonicalTemplateSpecializationType(Template, Args); } // Allocate the (non-canonical) template specialization type, but don't // try to unique it: these types typically have location information that // we don't unique and don't want to lose. void *Mem = Allocate(sizeof(TemplateSpecializationType) + sizeof(TemplateArgument) * Args.size() + (IsTypeAlias? sizeof(QualType) : 0), TypeAlignment); auto *Spec = new (Mem) TemplateSpecializationType(Template, Args, CanonType, IsTypeAlias ? Underlying : QualType()); Types.push_back(Spec); return QualType(Spec, 0); } QualType ASTContext::getCanonicalTemplateSpecializationType( TemplateName Template, ArrayRef<TemplateArgument> Args) const { assert(!Template.getAsDependentTemplateName() && "No dependent template names here!"); // Look through qualified template names. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) Template = TemplateName(QTN->getTemplateDecl()); // Build the canonical template specialization type. TemplateName CanonTemplate = getCanonicalTemplateName(Template); SmallVector<TemplateArgument, 4> CanonArgs; unsigned NumArgs = Args.size(); CanonArgs.reserve(NumArgs); for (const TemplateArgument &Arg : Args) CanonArgs.push_back(getCanonicalTemplateArgument(Arg)); // Determine whether this canonical template specialization type already // exists. llvm::FoldingSetNodeID ID; TemplateSpecializationType::Profile(ID, CanonTemplate, CanonArgs, *this); void *InsertPos = nullptr; TemplateSpecializationType *Spec = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); if (!Spec) { // Allocate a new canonical template specialization type. void *Mem = Allocate((sizeof(TemplateSpecializationType) + sizeof(TemplateArgument) * NumArgs), TypeAlignment); Spec = new (Mem) TemplateSpecializationType(CanonTemplate, CanonArgs, QualType(), QualType()); Types.push_back(Spec); TemplateSpecializationTypes.InsertNode(Spec, InsertPos); } assert(Spec->isDependentType() && "Non-dependent template-id type must have a canonical type"); return QualType(Spec, 0); } QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl) const { llvm::FoldingSetNodeID ID; ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl); void *InsertPos = nullptr; ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); if (T) return QualType(T, 0); QualType Canon = NamedType; if (!Canon.isCanonical()) { Canon = getCanonicalType(NamedType); ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!CheckT && "Elaborated canonical type broken"); (void)CheckT; } void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl), TypeAlignment); T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl); Types.push_back(T); ElaboratedTypes.InsertNode(T, InsertPos); return QualType(T, 0); } QualType ASTContext::getParenType(QualType InnerType) const { llvm::FoldingSetNodeID ID; ParenType::Profile(ID, InnerType); void *InsertPos = nullptr; ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); if (T) return QualType(T, 0); QualType Canon = InnerType; if (!Canon.isCanonical()) { Canon = getCanonicalType(InnerType); ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!CheckT && "Paren canonical type broken"); (void)CheckT; } T = new (*this, TypeAlignment) ParenType(InnerType, Canon); Types.push_back(T); ParenTypes.InsertNode(T, InsertPos); return QualType(T, 0); } QualType ASTContext::getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const { QualType Canon = UnderlyingTy; if (!Canon.isCanonical()) Canon = getCanonicalType(UnderlyingTy); auto *newType = new (*this, TypeAlignment) MacroQualifiedType(UnderlyingTy, Canon, MacroII); Types.push_back(newType); return QualType(newType, 0); } QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon) const { if (Canon.isNull()) { NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); if (CanonNNS != NNS) Canon = getDependentNameType(Keyword, CanonNNS, Name); } llvm::FoldingSetNodeID ID; DependentNameType::Profile(ID, Keyword, NNS, Name); void *InsertPos = nullptr; DependentNameType *T = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); if (T) return QualType(T, 0); T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon); Types.push_back(T); DependentNameTypes.InsertNode(T, InsertPos); return QualType(T, 0); } QualType ASTContext::getDependentTemplateSpecializationType( ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, const TemplateArgumentListInfo &Args) const { // TODO: avoid this copy SmallVector<TemplateArgument, 16> ArgCopy; for (unsigned I = 0, E = Args.size(); I != E; ++I) ArgCopy.push_back(Args[I].getArgument()); return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy); } QualType ASTContext::getDependentTemplateSpecializationType( ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const { assert((!NNS || NNS->isDependent()) && "nested-name-specifier must be dependent"); llvm::FoldingSetNodeID ID; DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, Name, Args); void *InsertPos = nullptr; DependentTemplateSpecializationType *T = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); if (T) return QualType(T, 0); NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); ElaboratedTypeKeyword CanonKeyword = Keyword; if (Keyword == ETK_None) CanonKeyword = ETK_Typename; bool AnyNonCanonArgs = false; unsigned NumArgs = Args.size(); SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); for (unsigned I = 0; I != NumArgs; ++I) { CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); if (!CanonArgs[I].structurallyEquals(Args[I])) AnyNonCanonArgs = true; } QualType Canon; if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, Name, CanonArgs); // Find the insert position again. DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); } void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + sizeof(TemplateArgument) * NumArgs), TypeAlignment); T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, Name, Args, Canon); Types.push_back(T); DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); return QualType(T, 0); } TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) { TemplateArgument Arg; if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { QualType ArgType = getTypeDeclType(TTP); if (TTP->isParameterPack()) ArgType = getPackExpansionType(ArgType, None); Arg = TemplateArgument(ArgType); } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { Expr *E = new (*this) DeclRefExpr( *this, NTTP, /*enclosing*/ false, NTTP->getType().getNonLValueExprType(*this), Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation()); if (NTTP->isParameterPack()) E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(), None); Arg = TemplateArgument(E); } else { auto *TTP = cast<TemplateTemplateParmDecl>(Param); if (TTP->isParameterPack()) Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>()); else Arg = TemplateArgument(TemplateName(TTP)); } if (Param->isTemplateParameterPack()) Arg = TemplateArgument::CreatePackCopy(*this, Arg); return Arg; } void ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params, SmallVectorImpl<TemplateArgument> &Args) { Args.reserve(Args.size() + Params->size()); for (NamedDecl *Param : *Params) Args.push_back(getInjectedTemplateArg(Param)); } QualType ASTContext::getPackExpansionType(QualType Pattern, Optional<unsigned> NumExpansions) { llvm::FoldingSetNodeID ID; PackExpansionType::Profile(ID, Pattern, NumExpansions); // A deduced type can deduce to a pack, eg // auto ...x = some_pack; // That declaration isn't (yet) valid, but is created as part of building an // init-capture pack: // [...x = some_pack] {} assert((Pattern->containsUnexpandedParameterPack() || Pattern->getContainedDeducedType()) && "Pack expansions must expand one or more parameter packs"); void *InsertPos = nullptr; PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); if (T) return QualType(T, 0); QualType Canon; if (!Pattern.isCanonical()) { Canon = getCanonicalType(Pattern); // The canonical type might not contain an unexpanded parameter pack, if it // contains an alias template specialization which ignores one of its // parameters. if (Canon->containsUnexpandedParameterPack()) { Canon = getPackExpansionType(Canon, NumExpansions); // Find the insert position again, in case we inserted an element into // PackExpansionTypes and invalidated our insert position. PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); } } T = new (*this, TypeAlignment) PackExpansionType(Pattern, Canon, NumExpansions); Types.push_back(T); PackExpansionTypes.InsertNode(T, InsertPos); return QualType(T, 0); } /// CmpProtocolNames - Comparison predicate for sorting protocols /// alphabetically. static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS) { return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName()); } static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { if (Protocols.empty()) return true; if (Protocols[0]->getCanonicalDecl() != Protocols[0]) return false; for (unsigned i = 1; i != Protocols.size(); ++i) if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || Protocols[i]->getCanonicalDecl() != Protocols[i]) return false; return true; } static void SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) { // Sort protocols, keyed by name. llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames); // Canonicalize. for (ObjCProtocolDecl *&P : Protocols) P = P->getCanonicalDecl(); // Remove duplicates. auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end()); Protocols.erase(ProtocolsEnd, Protocols.end()); } QualType ASTContext::getObjCObjectType(QualType BaseType, ObjCProtocolDecl * const *Protocols, unsigned NumProtocols) const { return getObjCObjectType(BaseType, {}, llvm::makeArrayRef(Protocols, NumProtocols), /*isKindOf=*/false); } QualType ASTContext::getObjCObjectType( QualType baseType, ArrayRef<QualType> typeArgs, ArrayRef<ObjCProtocolDecl *> protocols, bool isKindOf) const { // If the base type is an interface and there aren't any protocols or // type arguments to add, then the interface type will do just fine. if (typeArgs.empty() && protocols.empty() && !isKindOf && isa<ObjCInterfaceType>(baseType)) return baseType; // Look in the folding set for an existing type. llvm::FoldingSetNodeID ID; ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf); void *InsertPos = nullptr; if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(QT, 0); // Determine the type arguments to be used for canonicalization, // which may be explicitly specified here or written on the base // type. ArrayRef<QualType> effectiveTypeArgs = typeArgs; if (effectiveTypeArgs.empty()) { if (const auto *baseObject = baseType->getAs<ObjCObjectType>()) effectiveTypeArgs = baseObject->getTypeArgs(); } // Build the canonical type, which has the canonical base type and a // sorted-and-uniqued list of protocols and the type arguments // canonicalized. QualType canonical; bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(), effectiveTypeArgs.end(), [&](QualType type) { return type.isCanonical(); }); bool protocolsSorted = areSortedAndUniqued(protocols); if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) { // Determine the canonical type arguments. ArrayRef<QualType> canonTypeArgs; SmallVector<QualType, 4> canonTypeArgsVec; if (!typeArgsAreCanonical) { canonTypeArgsVec.reserve(effectiveTypeArgs.size()); for (auto typeArg : effectiveTypeArgs) canonTypeArgsVec.push_back(getCanonicalType(typeArg)); canonTypeArgs = canonTypeArgsVec; } else { canonTypeArgs = effectiveTypeArgs; } ArrayRef<ObjCProtocolDecl *> canonProtocols; SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec; if (!protocolsSorted) { canonProtocolsVec.append(protocols.begin(), protocols.end()); SortAndUniqueProtocols(canonProtocolsVec); canonProtocols = canonProtocolsVec; } else { canonProtocols = protocols; } canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs, canonProtocols, isKindOf); // Regenerate InsertPos. ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); } unsigned size = sizeof(ObjCObjectTypeImpl); size += typeArgs.size() * sizeof(QualType); size += protocols.size() * sizeof(ObjCProtocolDecl *); void *mem = Allocate(size, TypeAlignment); auto *T = new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, isKindOf); Types.push_back(T); ObjCObjectTypes.InsertNode(T, InsertPos); return QualType(T, 0); } /// Apply Objective-C protocol qualifiers to the given type. /// If this is for the canonical type of a type parameter, we can apply /// protocol qualifiers on the ObjCObjectPointerType. QualType ASTContext::applyObjCProtocolQualifiers(QualType type, ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, bool allowOnPointerType) const { hasError = false; if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) { return getObjCTypeParamType(objT->getDecl(), protocols); } // Apply protocol qualifiers to ObjCObjectPointerType. if (allowOnPointerType) { if (const auto *objPtr = dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) { const ObjCObjectType *objT = objPtr->getObjectType(); // Merge protocol lists and construct ObjCObjectType. SmallVector<ObjCProtocolDecl*, 8> protocolsVec; protocolsVec.append(objT->qual_begin(), objT->qual_end()); protocolsVec.append(protocols.begin(), protocols.end()); ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec; type = getObjCObjectType( objT->getBaseType(), objT->getTypeArgsAsWritten(), protocols, objT->isKindOfTypeAsWritten()); return getObjCObjectPointerType(type); } } // Apply protocol qualifiers to ObjCObjectType. if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){ // FIXME: Check for protocols to which the class type is already // known to conform. return getObjCObjectType(objT->getBaseType(), objT->getTypeArgsAsWritten(), protocols, objT->isKindOfTypeAsWritten()); } // If the canonical type is ObjCObjectType, ... if (type->isObjCObjectType()) { // Silently overwrite any existing protocol qualifiers. // TODO: determine whether that's the right thing to do. // FIXME: Check for protocols to which the class type is already // known to conform. return getObjCObjectType(type, {}, protocols, false); } // id<protocol-list> if (type->isObjCIdType()) { const auto *objPtr = type->castAs<ObjCObjectPointerType>(); type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols, objPtr->isKindOfType()); return getObjCObjectPointerType(type); } // Class<protocol-list> if (type->isObjCClassType()) { const auto *objPtr = type->castAs<ObjCObjectPointerType>(); type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols, objPtr->isKindOfType()); return getObjCObjectPointerType(type); } hasError = true; return type; } QualType ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef<ObjCProtocolDecl *> protocols) const { // Look in the folding set for an existing type. llvm::FoldingSetNodeID ID; ObjCTypeParamType::Profile(ID, Decl, protocols); void *InsertPos = nullptr; if (ObjCTypeParamType *TypeParam = ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(TypeParam, 0); // We canonicalize to the underlying type. QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); if (!protocols.empty()) { // Apply the protocol qualifers. bool hasError; Canonical = getCanonicalType(applyObjCProtocolQualifiers( Canonical, protocols, hasError, true /*allowOnPointerType*/)); assert(!hasError && "Error when apply protocol qualifier to bound type"); } unsigned size = sizeof(ObjCTypeParamType); size += protocols.size() * sizeof(ObjCProtocolDecl *); void *mem = Allocate(size, TypeAlignment); auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols); Types.push_back(newType); ObjCTypeParamTypes.InsertNode(newType, InsertPos); return QualType(newType, 0); } /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's /// protocol list adopt all protocols in QT's qualified-id protocol /// list. bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *IC) { if (!QT->isObjCQualifiedIdType()) return false; if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) { // If both the right and left sides have qualifiers. for (auto *Proto : OPT->quals()) { if (!IC->ClassImplementsProtocol(Proto, false)) return false; } return true; } return false; } /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in /// QT's qualified-id protocol list adopt all protocols in IDecl's list /// of protocols. bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl) { if (!QT->isObjCQualifiedIdType()) return false; const auto *OPT = QT->getAs<ObjCObjectPointerType>(); if (!OPT) return false; if (!IDecl->hasDefinition()) return false; llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; CollectInheritedProtocols(IDecl, InheritedProtocols); if (InheritedProtocols.empty()) return false; // Check that if every protocol in list of id<plist> conforms to a protocol // of IDecl's, then bridge casting is ok. bool Conforms = false; for (auto *Proto : OPT->quals()) { Conforms = false; for (auto *PI : InheritedProtocols) { if (ProtocolCompatibleWithProtocol(Proto, PI)) { Conforms = true; break; } } if (!Conforms) break; } if (Conforms) return true; for (auto *PI : InheritedProtocols) { // If both the right and left sides have qualifiers. bool Adopts = false; for (auto *Proto : OPT->quals()) { // return 'true' if 'PI' is in the inheritance hierarchy of Proto if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) break; } if (!Adopts) return false; } return true; } /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for /// the given object type. QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { llvm::FoldingSetNodeID ID; ObjCObjectPointerType::Profile(ID, ObjectT); void *InsertPos = nullptr; if (ObjCObjectPointerType *QT = ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(QT, 0); // Find the canonical object type. QualType Canonical; if (!ObjectT.isCanonical()) { Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); // Regenerate InsertPos. ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); } // No match. void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); auto *QType = new (Mem) ObjCObjectPointerType(Canonical, ObjectT); Types.push_back(QType); ObjCObjectPointerTypes.InsertNode(QType, InsertPos); return QualType(QType, 0); } /// getObjCInterfaceType - Return the unique reference to the type for the /// specified ObjC interface decl. The list of protocols is optional. QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl) const { if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); if (PrevDecl) { assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); Decl->TypeForDecl = PrevDecl->TypeForDecl; return QualType(PrevDecl->TypeForDecl, 0); } // Prefer the definition, if there is one. if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) Decl = Def; void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); auto *T = new (Mem) ObjCInterfaceType(Decl); Decl->TypeForDecl = T; Types.push_back(T); return QualType(T, 0); } /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique /// TypeOfExprType AST's (since expression's are never shared). For example, /// multiple declarations that refer to "typeof(x)" all contain different /// DeclRefExpr's. This doesn't effect the type checker, since it operates /// on canonical type's (which are always unique). QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { TypeOfExprType *toe; if (tofExpr->isTypeDependent()) { llvm::FoldingSetNodeID ID; DependentTypeOfExprType::Profile(ID, *this, tofExpr); void *InsertPos = nullptr; DependentTypeOfExprType *Canon = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); if (Canon) { // We already have a "canonical" version of an identical, dependent // typeof(expr) type. Use that as our canonical type. toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, QualType((TypeOfExprType*)Canon, 0)); } else { // Build a new, canonical typeof(expr) type. Canon = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); toe = Canon; } } else { QualType Canonical = getCanonicalType(tofExpr->getType()); toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); } Types.push_back(toe); return QualType(toe, 0); } /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique /// TypeOfType nodes. The only motivation to unique these nodes would be /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be /// an issue. This doesn't affect the type checker, since it operates /// on canonical types (which are always unique). QualType ASTContext::getTypeOfType(QualType tofType) const { QualType Canonical = getCanonicalType(tofType); auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); Types.push_back(tot); return QualType(tot, 0); } /// Unlike many "get<Type>" functions, we don't unique DecltypeType /// nodes. This would never be helpful, since each such type has its own /// expression, and would not give a significant memory saving, since there /// is an Expr tree under each such type. QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { DecltypeType *dt; // C++11 [temp.type]p2: // If an expression e involves a template parameter, decltype(e) denotes a // unique dependent type. Two such decltype-specifiers refer to the same // type only if their expressions are equivalent (14.5.6.1). if (e->isInstantiationDependent()) { llvm::FoldingSetNodeID ID; DependentDecltypeType::Profile(ID, *this, e); void *InsertPos = nullptr; DependentDecltypeType *Canon = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); if (!Canon) { // Build a new, canonical decltype(expr) type. Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); DependentDecltypeTypes.InsertNode(Canon, InsertPos); } dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); } else { dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); } Types.push_back(dt); return QualType(dt, 0); } /// getUnaryTransformationType - We don't unique these, since the memory /// savings are minimal and these are rare. QualType ASTContext::getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind Kind) const { UnaryTransformType *ut = nullptr; if (BaseType->isDependentType()) { // Look in the folding set for an existing type. llvm::FoldingSetNodeID ID; DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind); void *InsertPos = nullptr; DependentUnaryTransformType *Canon = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); if (!Canon) { // Build a new, canonical __underlying_type(type) type. Canon = new (*this, TypeAlignment) DependentUnaryTransformType(*this, getCanonicalType(BaseType), Kind); DependentUnaryTransformTypes.InsertNode(Canon, InsertPos); } ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, QualType(), Kind, QualType(Canon, 0)); } else { QualType CanonType = getCanonicalType(UnderlyingType); ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType, Kind, CanonType); } Types.push_back(ut); return QualType(ut, 0); } /// getAutoType - Return the uniqued reference to the 'auto' type which has been /// deduced to the given type, or to the canonical undeduced 'auto' type, or the /// canonical deduced-but-dependent 'auto' type. QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack, ConceptDecl *TypeConstraintConcept, ArrayRef<TemplateArgument> TypeConstraintArgs) const { assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack"); if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !TypeConstraintConcept && !IsDependent) return getAutoDeductType(); // Look in the folding set for an existing type. void *InsertPos = nullptr; llvm::FoldingSetNodeID ID; AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent, TypeConstraintConcept, TypeConstraintArgs); if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(AT, 0); void *Mem = Allocate(sizeof(AutoType) + sizeof(TemplateArgument) * TypeConstraintArgs.size(), TypeAlignment); auto *AT = new (Mem) AutoType(DeducedType, Keyword, IsDependent, IsPack, TypeConstraintConcept, TypeConstraintArgs); Types.push_back(AT); if (InsertPos) AutoTypes.InsertNode(AT, InsertPos); return QualType(AT, 0); } /// Return the uniqued reference to the deduced template specialization type /// which has been deduced to the given type, or to the canonical undeduced /// such type, or the canonical deduced-but-dependent such type. QualType ASTContext::getDeducedTemplateSpecializationType( TemplateName Template, QualType DeducedType, bool IsDependent) const { // Look in the folding set for an existing type. void *InsertPos = nullptr; llvm::FoldingSetNodeID ID; DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType, IsDependent); if (DeducedTemplateSpecializationType *DTST = DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(DTST, 0); auto *DTST = new (*this, TypeAlignment) DeducedTemplateSpecializationType(Template, DeducedType, IsDependent); Types.push_back(DTST); if (InsertPos) DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos); return QualType(DTST, 0); } /// getAtomicType - Return the uniqued reference to the atomic type for /// the given value type. QualType ASTContext::getAtomicType(QualType T) const { // Unique pointers, to guarantee there is only one pointer of a particular // structure. llvm::FoldingSetNodeID ID; AtomicType::Profile(ID, T); void *InsertPos = nullptr; if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(AT, 0); // If the atomic value type isn't canonical, this won't be a canonical type // either, so fill in the canonical type field. QualType Canonical; if (!T.isCanonical()) { Canonical = getAtomicType(getCanonicalType(T)); // Get the new insert position for the node we care about. AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; } auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical); Types.push_back(New); AtomicTypes.InsertNode(New, InsertPos); return QualType(New, 0); } /// getAutoDeductType - Get type pattern for deducing against 'auto'. QualType ASTContext::getAutoDeductType() const { if (AutoDeductTy.isNull()) AutoDeductTy = QualType( new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto, /*dependent*/false, /*pack*/false, /*concept*/nullptr, /*args*/{}), 0); return AutoDeductTy; } /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. QualType ASTContext::getAutoRRefDeductType() const { if (AutoRRefDeductTy.isNull()) AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); return AutoRRefDeductTy; } /// getTagDeclType - Return the unique reference to the type for the /// specified TagDecl (struct/union/class/enum) decl. QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { assert(Decl); // FIXME: What is the design on getTagDeclType when it requires casting // away const? mutable? return getTypeDeclType(const_cast<TagDecl*>(Decl)); } /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and /// needs to agree with the definition in <stddef.h>. CanQualType ASTContext::getSizeType() const { return getFromTargetType(Target->getSizeType()); } /// Return the unique signed counterpart of the integer type /// corresponding to size_t. CanQualType ASTContext::getSignedSizeType() const { return getFromTargetType(Target->getSignedSizeType()); } /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). CanQualType ASTContext::getIntMaxType() const { return getFromTargetType(Target->getIntMaxType()); } /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). CanQualType ASTContext::getUIntMaxType() const { return getFromTargetType(Target->getUIntMaxType()); } /// getSignedWCharType - Return the type of "signed wchar_t". /// Used when in C++, as a GCC extension. QualType ASTContext::getSignedWCharType() const { // FIXME: derive from "Target" ? return WCharTy; } /// getUnsignedWCharType - Return the type of "unsigned wchar_t". /// Used when in C++, as a GCC extension. QualType ASTContext::getUnsignedWCharType() const { // FIXME: derive from "Target" ? return UnsignedIntTy; } QualType ASTContext::getIntPtrType() const { return getFromTargetType(Target->getIntPtrType()); } QualType ASTContext::getUIntPtrType() const { return getCorrespondingUnsignedType(getIntPtrType()); } /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). QualType ASTContext::getPointerDiffType() const { return getFromTargetType(Target->getPtrDiffType(0)); } /// Return the unique unsigned counterpart of "ptrdiff_t" /// integer type. The standard (C11 7.21.6.1p7) refers to this type /// in the definition of %tu format specifier. QualType ASTContext::getUnsignedPointerDiffType() const { return getFromTargetType(Target->getUnsignedPtrDiffType(0)); } /// Return the unique type for "pid_t" defined in /// <sys/types.h>. We need this to compute the correct type for vfork(). QualType ASTContext::getProcessIDType() const { return getFromTargetType(Target->getProcessIDType()); } //===----------------------------------------------------------------------===// // Type Operators //===----------------------------------------------------------------------===// CanQualType ASTContext::getCanonicalParamType(QualType T) const { // Push qualifiers into arrays, and then discard any remaining // qualifiers. T = getCanonicalType(T); T = getVariableArrayDecayedType(T); const Type *Ty = T.getTypePtr(); QualType Result; if (isa<ArrayType>(Ty)) { Result = getArrayDecayedType(QualType(Ty,0)); } else if (isa<FunctionType>(Ty)) { Result = getPointerType(QualType(Ty, 0)); } else { Result = QualType(Ty, 0); } return CanQualType::CreateUnsafe(Result); } QualType ASTContext::getUnqualifiedArrayType(QualType type, Qualifiers &quals) { SplitQualType splitType = type.getSplitUnqualifiedType(); // FIXME: getSplitUnqualifiedType() actually walks all the way to // the unqualified desugared type and then drops it on the floor. // We then have to strip that sugar back off with // getUnqualifiedDesugaredType(), which is silly. const auto *AT = dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); // If we don't have an array, just use the results in splitType. if (!AT) { quals = splitType.Quals; return QualType(splitType.Ty, 0); } // Otherwise, recurse on the array's element type. QualType elementType = AT->getElementType(); QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); // If that didn't change the element type, AT has no qualifiers, so we // can just use the results in splitType. if (elementType == unqualElementType) { assert(quals.empty()); // from the recursive call quals = splitType.Quals; return QualType(splitType.Ty, 0); } // Otherwise, add in the qualifiers from the outermost type, then // build the type back up. quals.addConsistentQualifiers(splitType.Quals); if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) { return getConstantArrayType(unqualElementType, CAT->getSize(), CAT->getSizeExpr(), CAT->getSizeModifier(), 0); } if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) { return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); } if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) { return getVariableArrayType(unqualElementType, VAT->getSizeExpr(), VAT->getSizeModifier(), VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange()); } const auto *DSAT = cast<DependentSizedArrayType>(AT); return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), DSAT->getSizeModifier(), 0, SourceRange()); } /// Attempt to unwrap two types that may both be array types with the same bound /// (or both be array types of unknown bound) for the purpose of comparing the /// cv-decomposition of two types per C++ [conv.qual]. bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) { bool UnwrappedAny = false; while (true) { auto *AT1 = getAsArrayType(T1); if (!AT1) return UnwrappedAny; auto *AT2 = getAsArrayType(T2); if (!AT2) return UnwrappedAny; // If we don't have two array types with the same constant bound nor two // incomplete array types, we've unwrapped everything we can. if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) { auto *CAT2 = dyn_cast<ConstantArrayType>(AT2); if (!CAT2 || CAT1->getSize() != CAT2->getSize()) return UnwrappedAny; } else if (!isa<IncompleteArrayType>(AT1) || !isa<IncompleteArrayType>(AT2)) { return UnwrappedAny; } T1 = AT1->getElementType(); T2 = AT2->getElementType(); UnwrappedAny = true; } } /// Attempt to unwrap two types that may be similar (C++ [conv.qual]). /// /// If T1 and T2 are both pointer types of the same kind, or both array types /// with the same bound, unwraps layers from T1 and T2 until a pointer type is /// unwrapped. Top-level qualifiers on T1 and T2 are ignored. /// /// This function will typically be called in a loop that successively /// "unwraps" pointer and pointer-to-member types to compare them at each /// level. /// /// \return \c true if a pointer type was unwrapped, \c false if we reached a /// pair of types that can't be unwrapped further. bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) { UnwrapSimilarArrayTypes(T1, T2); const auto *T1PtrType = T1->getAs<PointerType>(); const auto *T2PtrType = T2->getAs<PointerType>(); if (T1PtrType && T2PtrType) { T1 = T1PtrType->getPointeeType(); T2 = T2PtrType->getPointeeType(); return true; } const auto *T1MPType = T1->getAs<MemberPointerType>(); const auto *T2MPType = T2->getAs<MemberPointerType>(); if (T1MPType && T2MPType && hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), QualType(T2MPType->getClass(), 0))) { T1 = T1MPType->getPointeeType(); T2 = T2MPType->getPointeeType(); return true; } if (getLangOpts().ObjC) { const auto *T1OPType = T1->getAs<ObjCObjectPointerType>(); const auto *T2OPType = T2->getAs<ObjCObjectPointerType>(); if (T1OPType && T2OPType) { T1 = T1OPType->getPointeeType(); T2 = T2OPType->getPointeeType(); return true; } } // FIXME: Block pointers, too? return false; } bool ASTContext::hasSimilarType(QualType T1, QualType T2) { while (true) { Qualifiers Quals; T1 = getUnqualifiedArrayType(T1, Quals); T2 = getUnqualifiedArrayType(T2, Quals); if (hasSameType(T1, T2)) return true; if (!UnwrapSimilarTypes(T1, T2)) return false; } } bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) { while (true) { Qualifiers Quals1, Quals2; T1 = getUnqualifiedArrayType(T1, Quals1); T2 = getUnqualifiedArrayType(T2, Quals2); Quals1.removeCVRQualifiers(); Quals2.removeCVRQualifiers(); if (Quals1 != Quals2) return false; if (hasSameType(T1, T2)) return true; if (!UnwrapSimilarTypes(T1, T2)) return false; } } DeclarationNameInfo ASTContext::getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const { switch (Name.getKind()) { case TemplateName::QualifiedTemplate: case TemplateName::Template: // DNInfo work in progress: CHECKME: what about DNLoc? return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), NameLoc); case TemplateName::OverloadedTemplate: { OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); // DNInfo work in progress: CHECKME: what about DNLoc? return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); } case TemplateName::AssumedTemplate: { AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName(); return DeclarationNameInfo(Storage->getDeclName(), NameLoc); } case TemplateName::DependentTemplate: { DependentTemplateName *DTN = Name.getAsDependentTemplateName(); DeclarationName DName; if (DTN->isIdentifier()) { DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); return DeclarationNameInfo(DName, NameLoc); } else { DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); // DNInfo work in progress: FIXME: source locations? DeclarationNameLoc DNLoc; DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); return DeclarationNameInfo(DName, NameLoc, DNLoc); } } case TemplateName::SubstTemplateTemplateParm: { SubstTemplateTemplateParmStorage *subst = Name.getAsSubstTemplateTemplateParm(); return DeclarationNameInfo(subst->getParameter()->getDeclName(), NameLoc); } case TemplateName::SubstTemplateTemplateParmPack: { SubstTemplateTemplateParmPackStorage *subst = Name.getAsSubstTemplateTemplateParmPack(); return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), NameLoc); } } llvm_unreachable("bad template name kind!"); } TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { switch (Name.getKind()) { case TemplateName::QualifiedTemplate: case TemplateName::Template: { TemplateDecl *Template = Name.getAsTemplateDecl(); if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) Template = getCanonicalTemplateTemplateParmDecl(TTP); // The canonical template name is the canonical template declaration. return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); } case TemplateName::OverloadedTemplate: case TemplateName::AssumedTemplate: llvm_unreachable("cannot canonicalize unresolved template"); case TemplateName::DependentTemplate: { DependentTemplateName *DTN = Name.getAsDependentTemplateName(); assert(DTN && "Non-dependent template names must refer to template decls."); return DTN->CanonicalTemplateName; } case TemplateName::SubstTemplateTemplateParm: { SubstTemplateTemplateParmStorage *subst = Name.getAsSubstTemplateTemplateParm(); return getCanonicalTemplateName(subst->getReplacement()); } case TemplateName::SubstTemplateTemplateParmPack: { SubstTemplateTemplateParmPackStorage *subst = Name.getAsSubstTemplateTemplateParmPack(); TemplateTemplateParmDecl *canonParameter = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); TemplateArgument canonArgPack = getCanonicalTemplateArgument(subst->getArgumentPack()); return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); } } llvm_unreachable("bad template name!"); } bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { X = getCanonicalTemplateName(X); Y = getCanonicalTemplateName(Y); return X.getAsVoidPointer() == Y.getAsVoidPointer(); } TemplateArgument ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { switch (Arg.getKind()) { case TemplateArgument::Null: return Arg; case TemplateArgument::Expression: return Arg; case TemplateArgument::Declaration: { auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); return TemplateArgument(D, Arg.getParamTypeForDecl()); } case TemplateArgument::NullPtr: return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), /*isNullPtr*/true); case TemplateArgument::Template: return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); case TemplateArgument::TemplateExpansion: return TemplateArgument(getCanonicalTemplateName( Arg.getAsTemplateOrTemplatePattern()), Arg.getNumTemplateExpansions()); case TemplateArgument::Integral: return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); case TemplateArgument::Type: return TemplateArgument(getCanonicalType(Arg.getAsType())); case TemplateArgument::Pack: { if (Arg.pack_size() == 0) return Arg; auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; unsigned Idx = 0; for (TemplateArgument::pack_iterator A = Arg.pack_begin(), AEnd = Arg.pack_end(); A != AEnd; (void)++A, ++Idx) CanonArgs[Idx] = getCanonicalTemplateArgument(*A); return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); } } // Silence GCC warning llvm_unreachable("Unhandled template argument kind"); } NestedNameSpecifier * ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { if (!NNS) return nullptr; switch (NNS->getKind()) { case NestedNameSpecifier::Identifier: // Canonicalize the prefix but keep the identifier the same. return NestedNameSpecifier::Create(*this, getCanonicalNestedNameSpecifier(NNS->getPrefix()), NNS->getAsIdentifier()); case NestedNameSpecifier::Namespace: // A namespace is canonical; build a nested-name-specifier with // this namespace and no prefix. return NestedNameSpecifier::Create(*this, nullptr, NNS->getAsNamespace()->getOriginalNamespace()); case NestedNameSpecifier::NamespaceAlias: // A namespace is canonical; build a nested-name-specifier with // this namespace and no prefix. return NestedNameSpecifier::Create(*this, nullptr, NNS->getAsNamespaceAlias()->getNamespace() ->getOriginalNamespace()); case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: { QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); // If we have some kind of dependent-named type (e.g., "typename T::type"), // break it apart into its prefix and identifier, then reconsititute those // as the canonical nested-name-specifier. This is required to canonicalize // a dependent nested-name-specifier involving typedefs of dependent-name // types, e.g., // typedef typename T::type T1; // typedef typename T1::type T2; if (const auto *DNT = T->getAs<DependentNameType>()) return NestedNameSpecifier::Create(*this, DNT->getQualifier(), const_cast<IdentifierInfo *>(DNT->getIdentifier())); // Otherwise, just canonicalize the type, and force it to be a TypeSpec. // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the // first place? return NestedNameSpecifier::Create(*this, nullptr, false, const_cast<Type *>(T.getTypePtr())); } case NestedNameSpecifier::Global: case NestedNameSpecifier::Super: // The global specifier and __super specifer are canonical and unique. return NNS; } llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); } const ArrayType *ASTContext::getAsArrayType(QualType T) const { // Handle the non-qualified case efficiently. if (!T.hasLocalQualifiers()) { // Handle the common positive case fast. if (const auto *AT = dyn_cast<ArrayType>(T)) return AT; } // Handle the common negative case fast. if (!isa<ArrayType>(T.getCanonicalType())) return nullptr; // Apply any qualifiers from the array type to the element type. This // implements C99 6.7.3p8: "If the specification of an array type includes // any type qualifiers, the element type is so qualified, not the array type." // If we get here, we either have type qualifiers on the type, or we have // sugar such as a typedef in the way. If we have type qualifiers on the type // we must propagate them down into the element type. SplitQualType split = T.getSplitDesugaredType(); Qualifiers qs = split.Quals; // If we have a simple case, just return now. const auto *ATy = dyn_cast<ArrayType>(split.Ty); if (!ATy || qs.empty()) return ATy; // Otherwise, we have an array and we have qualifiers on it. Push the // qualifiers into the array element type and return a new array type. QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy)) return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), CAT->getSizeExpr(), CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers())); if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy)) return cast<ArrayType>(getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(), IAT->getIndexTypeCVRQualifiers())); if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy)) return cast<ArrayType>( getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(), DSAT->getIndexTypeCVRQualifiers(), DSAT->getBracketsRange())); const auto *VAT = cast<VariableArrayType>(ATy); return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(), VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange())); } QualType ASTContext::getAdjustedParameterType(QualType T) const { if (T->isArrayType() || T->isFunctionType()) return getDecayedType(T); return T; } QualType ASTContext::getSignatureParameterType(QualType T) const { T = getVariableArrayDecayedType(T); T = getAdjustedParameterType(T); return T.getUnqualifiedType(); } QualType ASTContext::getExceptionObjectType(QualType T) const { // C++ [except.throw]p3: // A throw-expression initializes a temporary object, called the exception // object, the type of which is determined by removing any top-level // cv-qualifiers from the static type of the operand of throw and adjusting // the type from "array of T" or "function returning T" to "pointer to T" // or "pointer to function returning T", [...] T = getVariableArrayDecayedType(T); if (T->isArrayType() || T->isFunctionType()) T = getDecayedType(T); return T.getUnqualifiedType(); } /// getArrayDecayedType - Return the properly qualified result of decaying the /// specified array type to a pointer. This operation is non-trivial when /// handling typedefs etc. The canonical type of "T" must be an array type, /// this returns a pointer to a properly qualified element of the array. /// /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. QualType ASTContext::getArrayDecayedType(QualType Ty) const { // Get the element type with 'getAsArrayType' so that we don't lose any // typedefs in the element type of the array. This also handles propagation // of type qualifiers from the array type into the element type if present // (C99 6.7.3p8). const ArrayType *PrettyArrayType = getAsArrayType(Ty); assert(PrettyArrayType && "Not an array type!"); QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); // int x[restrict 4] -> int *restrict QualType Result = getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers()); // int x[_Nullable] -> int * _Nullable if (auto Nullability = Ty->getNullability(*this)) { Result = const_cast<ASTContext *>(this)->getAttributedType( AttributedType::getNullabilityAttrKind(*Nullability), Result, Result); } return Result; } QualType ASTContext::getBaseElementType(const ArrayType *array) const { return getBaseElementType(array->getElementType()); } QualType ASTContext::getBaseElementType(QualType type) const { Qualifiers qs; while (true) { SplitQualType split = type.getSplitDesugaredType(); const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); if (!array) break; type = array->getElementType(); qs.addConsistentQualifiers(split.Quals); } return getQualifiedType(type, qs); } /// getConstantArrayElementCount - Returns number of constant array elements. uint64_t ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { uint64_t ElementCount = 1; do { ElementCount *= CA->getSize().getZExtValue(); CA = dyn_cast_or_null<ConstantArrayType>( CA->getElementType()->getAsArrayTypeUnsafe()); } while (CA); return ElementCount; } /// getFloatingRank - Return a relative rank for floating point types. /// This routine will assert if passed a built-in type that isn't a float. static FloatingRank getFloatingRank(QualType T) { if (const auto *CT = T->getAs<ComplexType>()) return getFloatingRank(CT->getElementType()); switch (T->castAs<BuiltinType>()->getKind()) { default: llvm_unreachable("getFloatingRank(): not a floating type"); case BuiltinType::Float16: return Float16Rank; case BuiltinType::Half: return HalfRank; case BuiltinType::Float: return FloatRank; case BuiltinType::Double: return DoubleRank; case BuiltinType::LongDouble: return LongDoubleRank; case BuiltinType::Float128: return Float128Rank; } } /// getFloatingTypeOfSizeWithinDomain - Returns a real floating /// point or a complex type (based on typeDomain/typeSize). /// 'typeDomain' is a real floating point or complex type. /// 'typeSize' is a real floating point or complex type. QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, QualType Domain) const { FloatingRank EltRank = getFloatingRank(Size); if (Domain->isComplexType()) { switch (EltRank) { case Float16Rank: case HalfRank: llvm_unreachable("Complex half is not supported"); case FloatRank: return FloatComplexTy; case DoubleRank: return DoubleComplexTy; case LongDoubleRank: return LongDoubleComplexTy; case Float128Rank: return Float128ComplexTy; } } assert(Domain->isRealFloatingType() && "Unknown domain!"); switch (EltRank) { case Float16Rank: return HalfTy; case HalfRank: return HalfTy; case FloatRank: return FloatTy; case DoubleRank: return DoubleTy; case LongDoubleRank: return LongDoubleTy; case Float128Rank: return Float128Ty; } llvm_unreachable("getFloatingRank(): illegal value for rank"); } /// getFloatingTypeOrder - Compare the rank of the two specified floating /// point types, ignoring the domain of the type (i.e. 'double' == /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If /// LHS < RHS, return -1. int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { FloatingRank LHSR = getFloatingRank(LHS); FloatingRank RHSR = getFloatingRank(RHS); if (LHSR == RHSR) return 0; if (LHSR > RHSR) return 1; return -1; } int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const { if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS)) return 0; return getFloatingTypeOrder(LHS, RHS); } /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This /// routine will assert if passed a built-in type that isn't an integer or enum, /// or if it is not canonicalized. unsigned ASTContext::getIntegerRank(const Type *T) const { assert(T->isCanonicalUnqualified() && "T should be canonicalized"); switch (cast<BuiltinType>(T)->getKind()) { default: llvm_unreachable("getIntegerRank(): not a built-in integer"); // Scaffold will use that rank for cbit and qbit as a result case BuiltinType::Abit: case BuiltinType::Cbit: case BuiltinType::Qbit: case BuiltinType::Qint: case BuiltinType::Bool: return 1 + (getIntWidth(BoolTy) << 3); case BuiltinType::Char_S: case BuiltinType::Char_U: case BuiltinType::SChar: case BuiltinType::UChar: return 2 + (getIntWidth(CharTy) << 3); case BuiltinType::Short: case BuiltinType::UShort: return 3 + (getIntWidth(ShortTy) << 3); case BuiltinType::Int: case BuiltinType::UInt: return 4 + (getIntWidth(IntTy) << 3); case BuiltinType::Long: case BuiltinType::ULong: return 5 + (getIntWidth(LongTy) << 3); case BuiltinType::LongLong: case BuiltinType::ULongLong: return 6 + (getIntWidth(LongLongTy) << 3); case BuiltinType::Int128: case BuiltinType::UInt128: return 7 + (getIntWidth(Int128Ty) << 3); } } /// Whether this is a promotable bitfield reference according /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). /// /// \returns the type this bit-field will promote to, or NULL if no /// promotion occurs. QualType ASTContext::isPromotableBitField(Expr *E) const { if (E->isTypeDependent() || E->isValueDependent()) return {}; // C++ [conv.prom]p5: // If the bit-field has an enumerated type, it is treated as any other // value of that type for promotion purposes. if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) return {}; // FIXME: We should not do this unless E->refersToBitField() is true. This // matters in C where getSourceBitField() will find bit-fields for various // cases where the source expression is not a bit-field designator. FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? if (!Field) return {}; QualType FT = Field->getType(); uint64_t BitWidth = Field->getBitWidthValue(*this); uint64_t IntSize = getTypeSize(IntTy); // C++ [conv.prom]p5: // A prvalue for an integral bit-field can be converted to a prvalue of type // int if int can represent all the values of the bit-field; otherwise, it // can be converted to unsigned int if unsigned int can represent all the // values of the bit-field. If the bit-field is larger yet, no integral // promotion applies to it. // C11 6.3.1.1/2: // [For a bit-field of type _Bool, int, signed int, or unsigned int:] // If an int can represent all values of the original type (as restricted by // the width, for a bit-field), the value is converted to an int; otherwise, // it is converted to an unsigned int. // // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. // We perform that promotion here to match GCC and C++. // FIXME: C does not permit promotion of an enum bit-field whose rank is // greater than that of 'int'. We perform that promotion to match GCC. if (BitWidth < IntSize) return IntTy; if (BitWidth == IntSize) return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; // Bit-fields wider than int are not subject to promotions, and therefore act // like the base type. GCC has some weird bugs in this area that we // deliberately do not follow (GCC follows a pre-standard resolution to // C's DR315 which treats bit-width as being part of the type, and this leaks // into their semantics in some cases). return {}; } /// getPromotedIntegerType - Returns the type that Promotable will /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable /// integer type. QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { assert(!Promotable.isNull()); assert(Promotable->isPromotableIntegerType()); if (const auto *ET = Promotable->getAs<EnumType>()) return ET->getDecl()->getPromotionType(); if (const auto *BT = Promotable->getAs<BuiltinType>()) { // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t // (3.9.1) can be converted to a prvalue of the first of the following // types that can represent all the values of its underlying type: // int, unsigned int, long int, unsigned long int, long long int, or // unsigned long long int [...] // FIXME: Is there some better way to compute this? if (BT->getKind() == BuiltinType::WChar_S || BT->getKind() == BuiltinType::WChar_U || BT->getKind() == BuiltinType::Char8 || BT->getKind() == BuiltinType::Char16 || BT->getKind() == BuiltinType::Char32) { bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; uint64_t FromSize = getTypeSize(BT); QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, LongLongTy, UnsignedLongLongTy }; for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); if (FromSize < ToSize || (FromSize == ToSize && FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) return PromoteTypes[Idx]; } llvm_unreachable("char type should fit into long long"); } } // At this point, we should have a signed or unsigned integer type. if (Promotable->isSignedIntegerType()) return IntTy; uint64_t PromotableSize = getIntWidth(Promotable); uint64_t IntSize = getIntWidth(IntTy); assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; } /// Recurses in pointer/array types until it finds an objc retainable /// type and returns its ownership. Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { while (!T.isNull()) { if (T.getObjCLifetime() != Qualifiers::OCL_None) return T.getObjCLifetime(); if (T->isArrayType()) T = getBaseElementType(T); else if (const auto *PT = T->getAs<PointerType>()) T = PT->getPointeeType(); else if (const auto *RT = T->getAs<ReferenceType>()) T = RT->getPointeeType(); else break; } return Qualifiers::OCL_None; } static const Type *getIntegerTypeForEnum(const EnumType *ET) { // Incomplete enum types are not treated as integer types. // FIXME: In C++, enum types are never integer types. if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) return ET->getDecl()->getIntegerType().getTypePtr(); return nullptr; } /// getIntegerTypeOrder - Returns the highest ranked integer type: /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If /// LHS < RHS, return -1. int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { const Type *LHSC = getCanonicalType(LHS).getTypePtr(); const Type *RHSC = getCanonicalType(RHS).getTypePtr(); // Unwrap enums to their underlying type. if (const auto *ET = dyn_cast<EnumType>(LHSC)) LHSC = getIntegerTypeForEnum(ET); if (const auto *ET = dyn_cast<EnumType>(RHSC)) RHSC = getIntegerTypeForEnum(ET); if (LHSC == RHSC) return 0; bool LHSUnsigned = LHSC->isUnsignedIntegerType(); bool RHSUnsigned = RHSC->isUnsignedIntegerType(); unsigned LHSRank = getIntegerRank(LHSC); unsigned RHSRank = getIntegerRank(RHSC); if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. if (LHSRank == RHSRank) return 0; return LHSRank > RHSRank ? 1 : -1; } // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. if (LHSUnsigned) { // If the unsigned [LHS] type is larger, return it. if (LHSRank >= RHSRank) return 1; // If the signed type can represent all values of the unsigned type, it // wins. Because we are dealing with 2's complement and types that are // powers of two larger than each other, this is always safe. return -1; } // If the unsigned [RHS] type is larger, return it. if (RHSRank >= LHSRank) return -1; // If the signed type can represent all values of the unsigned type, it // wins. Because we are dealing with 2's complement and types that are // powers of two larger than each other, this is always safe. return 1; } TypedefDecl *ASTContext::getCFConstantStringDecl() const { if (CFConstantStringTypeDecl) return CFConstantStringTypeDecl; assert(!CFConstantStringTagDecl && "tag and typedef should be initialized together"); CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag"); CFConstantStringTagDecl->startDefinition(); struct { QualType Type; const char *Name; } Fields[5]; unsigned Count = 0; /// Objective-C ABI /// /// typedef struct __NSConstantString_tag { /// const int *isa; /// int flags; /// const char *str; /// long length; /// } __NSConstantString; /// /// Swift ABI (4.1, 4.2) /// /// typedef struct __NSConstantString_tag { /// uintptr_t _cfisa; /// uintptr_t _swift_rc; /// _Atomic(uint64_t) _cfinfoa; /// const char *_ptr; /// uint32_t _length; /// } __NSConstantString; /// /// Swift ABI (5.0) /// /// typedef struct __NSConstantString_tag { /// uintptr_t _cfisa; /// uintptr_t _swift_rc; /// _Atomic(uint64_t) _cfinfoa; /// const char *_ptr; /// uintptr_t _length; /// } __NSConstantString; const auto CFRuntime = getLangOpts().CFRuntime; if (static_cast<unsigned>(CFRuntime) < static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) { Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" }; Fields[Count++] = { IntTy, "flags" }; Fields[Count++] = { getPointerType(CharTy.withConst()), "str" }; Fields[Count++] = { LongTy, "length" }; } else { Fields[Count++] = { getUIntPtrType(), "_cfisa" }; Fields[Count++] = { getUIntPtrType(), "_swift_rc" }; Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" }; Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" }; if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) Fields[Count++] = { IntTy, "_ptr" }; else Fields[Count++] = { getUIntPtrType(), "_ptr" }; } // Create fields for (unsigned i = 0; i < Count; ++i) { FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(), SourceLocation(), &Idents.get(Fields[i].Name), Fields[i].Type, /*TInfo=*/nullptr, /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); CFConstantStringTagDecl->addDecl(Field); } CFConstantStringTagDecl->completeDefinition(); // This type is designed to be compatible with NSConstantString, but cannot // use the same name, since NSConstantString is an interface. auto tagType = getTagDeclType(CFConstantStringTagDecl); CFConstantStringTypeDecl = buildImplicitTypedef(tagType, "__NSConstantString"); return CFConstantStringTypeDecl; } RecordDecl *ASTContext::getCFConstantStringTagDecl() const { if (!CFConstantStringTagDecl) getCFConstantStringDecl(); // Build the tag and the typedef. return CFConstantStringTagDecl; } // getCFConstantStringType - Return the type used for constant CFStrings. QualType ASTContext::getCFConstantStringType() const { return getTypedefType(getCFConstantStringDecl()); } QualType ASTContext::getObjCSuperType() const { if (ObjCSuperType.isNull()) { RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); TUDecl->addDecl(ObjCSuperTypeDecl); ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); } return ObjCSuperType; } void ASTContext::setCFConstantStringType(QualType T) { const auto *TD = T->castAs<TypedefType>(); CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl()); const auto *TagType = CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>(); CFConstantStringTagDecl = TagType->getDecl(); } QualType ASTContext::getBlockDescriptorType() const { if (BlockDescriptorType) return getTagDeclType(BlockDescriptorType); RecordDecl *RD; // FIXME: Needs the FlagAppleBlock bit. RD = buildImplicitRecord("__block_descriptor"); RD->startDefinition(); QualType FieldTypes[] = { UnsignedLongTy, UnsignedLongTy, }; static const char *const FieldNames[] = { "reserved", "Size" }; for (size_t i = 0; i < 2; ++i) { FieldDecl *Field = FieldDecl::Create( *this, RD, SourceLocation(), SourceLocation(), &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); RD->addDecl(Field); } RD->completeDefinition(); BlockDescriptorType = RD; return getTagDeclType(BlockDescriptorType); } QualType ASTContext::getBlockDescriptorExtendedType() const { if (BlockDescriptorExtendedType) return getTagDeclType(BlockDescriptorExtendedType); RecordDecl *RD; // FIXME: Needs the FlagAppleBlock bit. RD = buildImplicitRecord("__block_descriptor_withcopydispose"); RD->startDefinition(); QualType FieldTypes[] = { UnsignedLongTy, UnsignedLongTy, getPointerType(VoidPtrTy), getPointerType(VoidPtrTy) }; static const char *const FieldNames[] = { "reserved", "Size", "CopyFuncPtr", "DestroyFuncPtr" }; for (size_t i = 0; i < 4; ++i) { FieldDecl *Field = FieldDecl::Create( *this, RD, SourceLocation(), SourceLocation(), &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); RD->addDecl(Field); } RD->completeDefinition(); BlockDescriptorExtendedType = RD; return getTagDeclType(BlockDescriptorExtendedType); } TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const { const auto *BT = dyn_cast<BuiltinType>(T); if (!BT) { if (isa<PipeType>(T)) return TargetInfo::OCLTK_Pipe; return TargetInfo::OCLTK_Default; } switch (BT->getKind()) { #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ case BuiltinType::Id: \ return TargetInfo::OCLTK_Image; #include "clang/Basic/OpenCLImageTypes.def" case BuiltinType::OCLClkEvent: return TargetInfo::OCLTK_ClkEvent; case BuiltinType::OCLEvent: return TargetInfo::OCLTK_Event; case BuiltinType::OCLQueue: return TargetInfo::OCLTK_Queue; case BuiltinType::OCLReserveID: return TargetInfo::OCLTK_ReserveID; case BuiltinType::OCLSampler: return TargetInfo::OCLTK_Sampler; default: return TargetInfo::OCLTK_Default; } } LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const { return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)); } /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" /// requires copy/dispose. Note that this must match the logic /// in buildByrefHelpers. bool ASTContext::BlockRequiresCopying(QualType Ty, const VarDecl *D) { if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr(); if (!copyExpr && record->hasTrivialDestructor()) return false; return true; } // The block needs copy/destroy helpers if Ty is non-trivial to destructively // move or destroy. if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) return true; if (!Ty->isObjCRetainableType()) return false; Qualifiers qs = Ty.getQualifiers(); // If we have lifetime, that dominates. if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { switch (lifetime) { case Qualifiers::OCL_None: llvm_unreachable("impossible"); // These are just bits as far as the runtime is concerned. case Qualifiers::OCL_ExplicitNone: case Qualifiers::OCL_Autoreleasing: return false; // These cases should have been taken care of when checking the type's // non-triviality. case Qualifiers::OCL_Weak: case Qualifiers::OCL_Strong: llvm_unreachable("impossible"); } llvm_unreachable("fell out of lifetime switch!"); } return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || Ty->isObjCObjectPointerType()); } bool ASTContext::getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &LifeTime, bool &HasByrefExtendedLayout) const { if (!getLangOpts().ObjC || getLangOpts().getGC() != LangOptions::NonGC) return false; HasByrefExtendedLayout = false; if (Ty->isRecordType()) { HasByrefExtendedLayout = true; LifeTime = Qualifiers::OCL_None; } else if ((LifeTime = Ty.getObjCLifetime())) { // Honor the ARC qualifiers. } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) { // The MRR rule. LifeTime = Qualifiers::OCL_ExplicitNone; } else { LifeTime = Qualifiers::OCL_None; } return true; } TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { if (!ObjCInstanceTypeDecl) ObjCInstanceTypeDecl = buildImplicitTypedef(getObjCIdType(), "instancetype"); return ObjCInstanceTypeDecl; } // This returns true if a type has been typedefed to BOOL: // typedef <type> BOOL; static bool isTypeTypedefedAsBOOL(QualType T) { if (const auto *TT = dyn_cast<TypedefType>(T)) if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) return II->isStr("BOOL"); return false; } /// getObjCEncodingTypeSize returns size of type for objective-c encoding /// purpose. CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { if (!type->isIncompleteArrayType() && type->isIncompleteType()) return CharUnits::Zero(); CharUnits sz = getTypeSizeInChars(type); // Make all integer and enum types at least as large as an int if (sz.isPositive() && type->isIntegralOrEnumerationType()) sz = std::max(sz, getTypeSizeInChars(IntTy)); // Treat arrays as pointers, since that's how they're passed in. else if (type->isArrayType()) sz = getTypeSizeInChars(VoidPtrTy); return sz; } bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { return getTargetInfo().getCXXABI().isMicrosoft() && VD->isStaticDataMember() && VD->getType()->isIntegralOrEnumerationType() && !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); } ASTContext::InlineVariableDefinitionKind ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { if (!VD->isInline()) return InlineVariableDefinitionKind::None; // In almost all cases, it's a weak definition. auto *First = VD->getFirstDecl(); if (First->isInlineSpecified() || !First->isStaticDataMember()) return InlineVariableDefinitionKind::Weak; // If there's a file-context declaration in this translation unit, it's a // non-discardable definition. for (auto *D : VD->redecls()) if (D->getLexicalDeclContext()->isFileContext() && !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr())) return InlineVariableDefinitionKind::Strong; // If we've not seen one yet, we don't know. return InlineVariableDefinitionKind::WeakUnknown; } static std::string charUnitsToString(const CharUnits &CU) { return llvm::itostr(CU.getQuantity()); } /// getObjCEncodingForBlock - Return the encoded type for this block /// declaration. std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { std::string S; const BlockDecl *Decl = Expr->getBlockDecl(); QualType BlockTy = Expr->getType()->castAs<BlockPointerType>()->getPointeeType(); QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType(); // Encode result type. if (getLangOpts().EncodeExtendedBlockSig) getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S, true /*Extended*/); else getObjCEncodingForType(BlockReturnTy, S); // Compute size of all parameters. // Start with computing size of a pointer in number of bytes. // FIXME: There might(should) be a better way of doing this computation! CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); CharUnits ParmOffset = PtrSize; for (auto PI : Decl->parameters()) { QualType PType = PI->getType(); CharUnits sz = getObjCEncodingTypeSize(PType); if (sz.isZero()) continue; assert(sz.isPositive() && "BlockExpr - Incomplete param type"); ParmOffset += sz; } // Size of the argument frame S += charUnitsToString(ParmOffset); // Block pointer and offset. S += "@?0"; // Argument types. ParmOffset = PtrSize; for (auto PVDecl : Decl->parameters()) { QualType PType = PVDecl->getOriginalType(); if (const auto *AT = dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { // Use array's original type only if it has known number of // elements. if (!isa<ConstantArrayType>(AT)) PType = PVDecl->getType(); } else if (PType->isFunctionType()) PType = PVDecl->getType(); if (getLangOpts().EncodeExtendedBlockSig) getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, S, true /*Extended*/); else getObjCEncodingForType(PType, S); S += charUnitsToString(ParmOffset); ParmOffset += getObjCEncodingTypeSize(PType); } return S; } std::string ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { std::string S; // Encode result type. getObjCEncodingForType(Decl->getReturnType(), S); CharUnits ParmOffset; // Compute size of all parameters. for (auto PI : Decl->parameters()) { QualType PType = PI->getType(); CharUnits sz = getObjCEncodingTypeSize(PType); if (sz.isZero()) continue; assert(sz.isPositive() && "getObjCEncodingForFunctionDecl - Incomplete param type"); ParmOffset += sz; } S += charUnitsToString(ParmOffset); ParmOffset = CharUnits::Zero(); // Argument types. for (auto PVDecl : Decl->parameters()) { QualType PType = PVDecl->getOriginalType(); if (const auto *AT = dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { // Use array's original type only if it has known number of // elements. if (!isa<ConstantArrayType>(AT)) PType = PVDecl->getType(); } else if (PType->isFunctionType()) PType = PVDecl->getType(); getObjCEncodingForType(PType, S); S += charUnitsToString(ParmOffset); ParmOffset += getObjCEncodingTypeSize(PType); } return S; } /// getObjCEncodingForMethodParameter - Return the encoded type for a single /// method parameter or return type. If Extended, include class names and /// block object types. void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string& S, bool Extended) const { // Encode type qualifer, 'in', 'inout', etc. for the parameter. getObjCEncodingForTypeQualifier(QT, S); // Encode parameter type. ObjCEncOptions Options = ObjCEncOptions() .setExpandPointedToStructures() .setExpandStructures() .setIsOutermostType(); if (Extended) Options.setEncodeBlockParameters().setEncodeClassNames(); getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr); } /// getObjCEncodingForMethodDecl - Return the encoded type for this method /// declaration. std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended) const { // FIXME: This is not very efficient. // Encode return type. std::string S; getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), Decl->getReturnType(), S, Extended); // Compute size of all parameters. // Start with computing size of a pointer in number of bytes. // FIXME: There might(should) be a better way of doing this computation! CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); // The first two arguments (self and _cmd) are pointers; account for // their size. CharUnits ParmOffset = 2 * PtrSize; for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), E = Decl->sel_param_end(); PI != E; ++PI) { QualType PType = (*PI)->getType(); CharUnits sz = getObjCEncodingTypeSize(PType); if (sz.isZero()) continue; assert(sz.isPositive() && "getObjCEncodingForMethodDecl - Incomplete param type"); ParmOffset += sz; } S += charUnitsToString(ParmOffset); S += "@0:"; S += charUnitsToString(PtrSize); // Argument types. ParmOffset = 2 * PtrSize; for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), E = Decl->sel_param_end(); PI != E; ++PI) { const ParmVarDecl *PVDecl = *PI; QualType PType = PVDecl->getOriginalType(); if (const auto *AT = dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { // Use array's original type only if it has known number of // elements. if (!isa<ConstantArrayType>(AT)) PType = PVDecl->getType(); } else if (PType->isFunctionType()) PType = PVDecl->getType(); getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), PType, S, Extended); S += charUnitsToString(ParmOffset); ParmOffset += getObjCEncodingTypeSize(PType); } return S; } ObjCPropertyImplDecl * ASTContext::getObjCPropertyImplDeclForPropertyDecl( const ObjCPropertyDecl *PD, const Decl *Container) const { if (!Container) return nullptr; if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) { for (auto *PID : CID->property_impls()) if (PID->getPropertyDecl() == PD) return PID; } else { const auto *OID = cast<ObjCImplementationDecl>(Container); for (auto *PID : OID->property_impls()) if (PID->getPropertyDecl() == PD) return PID; } return nullptr; } /// getObjCEncodingForPropertyDecl - Return the encoded type for this /// property declaration. If non-NULL, Container must be either an /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be /// NULL when getting encodings for protocol properties. /// Property attributes are stored as a comma-delimited C string. The simple /// attributes readonly and bycopy are encoded as single characters. The /// parametrized attributes, getter=name, setter=name, and ivar=name, are /// encoded as single characters, followed by an identifier. Property types /// are also encoded as a parametrized attribute. The characters used to encode /// these attributes are defined by the following enumeration: /// @code /// enum PropertyAttributes { /// kPropertyReadOnly = 'R', // property is read-only. /// kPropertyBycopy = 'C', // property is a copy of the value last assigned /// kPropertyByref = '&', // property is a reference to the value last assigned /// kPropertyDynamic = 'D', // property is dynamic /// kPropertyGetter = 'G', // followed by getter selector name /// kPropertySetter = 'S', // followed by setter selector name /// kPropertyInstanceVariable = 'V' // followed by instance variable name /// kPropertyType = 'T' // followed by old-style type encoding. /// kPropertyWeak = 'W' // 'weak' property /// kPropertyStrong = 'P' // property GC'able /// kPropertyNonAtomic = 'N' // property non-atomic /// }; /// @endcode std::string ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const { // Collect information from the property implementation decl(s). bool Dynamic = false; ObjCPropertyImplDecl *SynthesizePID = nullptr; if (ObjCPropertyImplDecl *PropertyImpDecl = getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) Dynamic = true; else SynthesizePID = PropertyImpDecl; } // FIXME: This is not very efficient. std::string S = "T"; // Encode result type. // GCC has some special rules regarding encoding of properties which // closely resembles encoding of ivars. getObjCEncodingForPropertyType(PD->getType(), S); if (PD->isReadOnly()) { S += ",R"; if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) S += ",C"; if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) S += ",&"; if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak) S += ",W"; } else { switch (PD->getSetterKind()) { case ObjCPropertyDecl::Assign: break; case ObjCPropertyDecl::Copy: S += ",C"; break; case ObjCPropertyDecl::Retain: S += ",&"; break; case ObjCPropertyDecl::Weak: S += ",W"; break; } } // It really isn't clear at all what this means, since properties // are "dynamic by default". if (Dynamic) S += ",D"; if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) S += ",N"; if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { S += ",G"; S += PD->getGetterName().getAsString(); } if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { S += ",S"; S += PD->getSetterName().getAsString(); } if (SynthesizePID) { const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); S += ",V"; S += OID->getNameAsString(); } // FIXME: OBJCGC: weak & strong return S; } /// getLegacyIntegralTypeEncoding - /// Another legacy compatibility encoding: 32-bit longs are encoded as /// 'l' or 'L' , but not always. For typedefs, we need to use /// 'i' or 'I' instead if encoding a struct field, or a pointer! void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { if (isa<TypedefType>(PointeeTy.getTypePtr())) { if (const auto *BT = PointeeTy->getAs<BuiltinType>()) { if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) PointeeTy = UnsignedIntTy; else if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) PointeeTy = IntTy; } } } void ASTContext::getObjCEncodingForType(QualType T, std::string& S, const FieldDecl *Field, QualType *NotEncodedT) const { // We follow the behavior of gcc, expanding structures which are // directly pointed to, and expanding embedded structures. Note that // these rules are sufficient to prevent recursive encoding of the // same type. getObjCEncodingForTypeImpl(T, S, ObjCEncOptions() .setExpandPointedToStructures() .setExpandStructures() .setIsOutermostType(), Field, NotEncodedT); } void ASTContext::getObjCEncodingForPropertyType(QualType T, std::string& S) const { // Encode result type. // GCC has some special rules regarding encoding of properties which // closely resembles encoding of ivars. getObjCEncodingForTypeImpl(T, S, ObjCEncOptions() .setExpandPointedToStructures() .setExpandStructures() .setIsOutermostType() .setEncodingProperty(), /*Field=*/nullptr); } static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT) { BuiltinType::Kind kind = BT->getKind(); switch (kind) { case BuiltinType::Void: return 'v'; case BuiltinType::Bool: return 'B'; case BuiltinType::Char8: case BuiltinType::Char_U: case BuiltinType::UChar: return 'C'; case BuiltinType::Char16: case BuiltinType::UShort: return 'S'; case BuiltinType::Char32: case BuiltinType::UInt: return 'I'; case BuiltinType::ULong: return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; case BuiltinType::UInt128: return 'T'; case BuiltinType::ULongLong: return 'Q'; case BuiltinType::Char_S: case BuiltinType::SChar: return 'c'; case BuiltinType::Short: return 's'; case BuiltinType::WChar_S: case BuiltinType::WChar_U: case BuiltinType::Int: return 'i'; case BuiltinType::Long: return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; case BuiltinType::LongLong: return 'q'; case BuiltinType::Int128: return 't'; case BuiltinType::Float: return 'f'; case BuiltinType::Double: return 'd'; case BuiltinType::LongDouble: return 'D'; case BuiltinType::NullPtr: return '*'; // like char* // Scaffold types // -- FIXME collision between cbit and qbit values, may cause other problems case BuiltinType::Abit: return 'a'; case BuiltinType::Cbit: return 'l'; case BuiltinType::Qbit: return 'q'; case BuiltinType::zzBit: case BuiltinType::zgBit: case BuiltinType::ooBit: case BuiltinType::ogBit: case BuiltinType::Qint: return 'y'; case BuiltinType::Float16: case BuiltinType::Float128: case BuiltinType::Half: case BuiltinType::ShortAccum: case BuiltinType::Accum: case BuiltinType::LongAccum: case BuiltinType::UShortAccum: case BuiltinType::UAccum: case BuiltinType::ULongAccum: case BuiltinType::ShortFract: case BuiltinType::Fract: case BuiltinType::LongFract: case BuiltinType::UShortFract: case BuiltinType::UFract: case BuiltinType::ULongFract: case BuiltinType::SatShortAccum: case BuiltinType::SatAccum: case BuiltinType::SatLongAccum: case BuiltinType::SatUShortAccum: case BuiltinType::SatUAccum: case BuiltinType::SatULongAccum: case BuiltinType::SatShortFract: case BuiltinType::SatFract: case BuiltinType::SatLongFract: case BuiltinType::SatUShortFract: case BuiltinType::SatUFract: case BuiltinType::SatULongFract: // FIXME: potentially need @encodes for these! return ' '; #define SVE_TYPE(Name, Id, SingletonId) \ case BuiltinType::Id: #include "clang/Basic/AArch64SVEACLETypes.def" { DiagnosticsEngine &Diags = C->getDiagnostics(); unsigned DiagID = Diags.getCustomDiagID( DiagnosticsEngine::Error, "cannot yet @encode type %0"); Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy()); return ' '; } case BuiltinType::ObjCId: case BuiltinType::ObjCClass: case BuiltinType::ObjCSel: llvm_unreachable("@encoding ObjC primitive type"); // OpenCL and placeholder types don't need @encodings. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ case BuiltinType::Id: #include "clang/Basic/OpenCLImageTypes.def" #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ case BuiltinType::Id: #include "clang/Basic/OpenCLExtensionTypes.def" case BuiltinType::OCLEvent: case BuiltinType::OCLClkEvent: case BuiltinType::OCLQueue: case BuiltinType::OCLReserveID: case BuiltinType::OCLSampler: case BuiltinType::Dependent: #define BUILTIN_TYPE(KIND, ID) #define PLACEHOLDER_TYPE(KIND, ID) \ case BuiltinType::KIND: #include "clang/AST/BuiltinTypes.def" llvm_unreachable("invalid builtin type for @encode"); } llvm_unreachable("invalid BuiltinType::Kind value"); } static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { EnumDecl *Enum = ET->getDecl(); // The encoding of an non-fixed enum type is always 'i', regardless of size. if (!Enum->isFixed()) return 'i'; // The encoding of a fixed enum type matches its fixed underlying type. const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>(); return getObjCEncodingForPrimitiveType(C, BT); } static void EncodeBitField(const ASTContext *Ctx, std::string& S, QualType T, const FieldDecl *FD) { assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); S += 'b'; // The NeXT runtime encodes bit fields as b followed by the number of bits. // The GNU runtime requires more information; bitfields are encoded as b, // then the offset (in bits) of the first element, then the type of the // bitfield, then the size in bits. For example, in this structure: // // struct // { // int integer; // int flags:2; // }; // On a 32-bit system, the encoding for flags would be b2 for the NeXT // runtime, but b32i2 for the GNU runtime. The reason for this extra // information is not especially sensible, but we're stuck with it for // compatibility with GCC, although providing it breaks anything that // actually uses runtime introspection and wants to work on both runtimes... if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { uint64_t Offset; if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) { Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, IVD); } else { const RecordDecl *RD = FD->getParent(); const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); Offset = RL.getFieldOffset(FD->getFieldIndex()); } S += llvm::utostr(Offset); if (const auto *ET = T->getAs<EnumType>()) S += ObjCEncodingForEnumType(Ctx, ET); else { const auto *BT = T->castAs<BuiltinType>(); S += getObjCEncodingForPrimitiveType(Ctx, BT); } } S += llvm::utostr(FD->getBitWidthValue(*Ctx)); } // FIXME: Use SmallString for accumulating string. void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S, const ObjCEncOptions Options, const FieldDecl *FD, QualType *NotEncodedT) const { CanQualType CT = getCanonicalType(T); switch (CT->getTypeClass()) { case Type::Builtin: case Type::Enum: if (FD && FD->isBitField()) return EncodeBitField(this, S, T, FD); if (const auto *BT = dyn_cast<BuiltinType>(CT)) S += getObjCEncodingForPrimitiveType(this, BT); else S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); return; case Type::Complex: S += 'j'; getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S, ObjCEncOptions(), /*Field=*/nullptr); return; case Type::Atomic: S += 'A'; getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S, ObjCEncOptions(), /*Field=*/nullptr); return; // encoding for pointer or reference types. case Type::Pointer: case Type::LValueReference: case Type::RValueReference: { QualType PointeeTy; if (isa<PointerType>(CT)) { const auto *PT = T->castAs<PointerType>(); if (PT->isObjCSelType()) { S += ':'; return; } PointeeTy = PT->getPointeeType(); } else { PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); } bool isReadOnly = false; // For historical/compatibility reasons, the read-only qualifier of the // pointee gets emitted _before_ the '^'. The read-only qualifier of // the pointer itself gets ignored, _unless_ we are looking at a typedef! // Also, do not emit the 'r' for anything but the outermost type! if (isa<TypedefType>(T.getTypePtr())) { if (Options.IsOutermostType() && T.isConstQualified()) { isReadOnly = true; S += 'r'; } } else if (Options.IsOutermostType()) { QualType P = PointeeTy; while (auto PT = P->getAs<PointerType>()) P = PT->getPointeeType(); if (P.isConstQualified()) { isReadOnly = true; S += 'r'; } } if (isReadOnly) { // Another legacy compatibility encoding. Some ObjC qualifier and type // combinations need to be rearranged. // Rewrite "in const" from "nr" to "rn" if (StringRef(S).endswith("nr")) S.replace(S.end()-2, S.end(), "rn"); } if (PointeeTy->isCharType()) { // char pointer types should be encoded as '*' unless it is a // type that has been typedef'd to 'BOOL'. if (!isTypeTypedefedAsBOOL(PointeeTy)) { S += '*'; return; } } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) { // GCC binary compat: Need to convert "struct objc_class *" to "#". if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { S += '#'; return; } // GCC binary compat: Need to convert "struct objc_object *" to "@". if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { S += '@'; return; } // fall through... } S += '^'; getLegacyIntegralTypeEncoding(PointeeTy); ObjCEncOptions NewOptions; if (Options.ExpandPointedToStructures()) NewOptions.setExpandStructures(); getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions, /*Field=*/nullptr, NotEncodedT); return; } case Type::ConstantArray: case Type::IncompleteArray: case Type::VariableArray: { const auto *AT = cast<ArrayType>(CT); if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) { // Incomplete arrays are encoded as a pointer to the array element. S += '^'; getObjCEncodingForTypeImpl( AT->getElementType(), S, Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD); } else { S += '['; if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) S += llvm::utostr(CAT->getSize().getZExtValue()); else { //Variable length arrays are encoded as a regular array with 0 elements. assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && "Unknown array type!"); S += '0'; } getObjCEncodingForTypeImpl( AT->getElementType(), S, Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD, NotEncodedT); S += ']'; } return; } case Type::FunctionNoProto: case Type::FunctionProto: S += '?'; return; case Type::Record: { RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); S += RDecl->isUnion() ? '(' : '{'; // Anonymous structures print as '?' if (const IdentifierInfo *II = RDecl->getIdentifier()) { S += II->getName(); if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); llvm::raw_string_ostream OS(S); printTemplateArgumentList(OS, TemplateArgs.asArray(), getPrintingPolicy()); } } else { S += '?'; } if (Options.ExpandStructures()) { S += '='; if (!RDecl->isUnion()) { getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); } else { for (const auto *Field : RDecl->fields()) { if (FD) { S += '"'; S += Field->getNameAsString(); S += '"'; } // Special case bit-fields. if (Field->isBitField()) { getObjCEncodingForTypeImpl(Field->getType(), S, ObjCEncOptions().setExpandStructures(), Field); } else { QualType qt = Field->getType(); getLegacyIntegralTypeEncoding(qt); getObjCEncodingForTypeImpl( qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(), FD, NotEncodedT); } } } } S += RDecl->isUnion() ? ')' : '}'; return; } case Type::BlockPointer: { const auto *BT = T->castAs<BlockPointerType>(); S += "@?"; // Unlike a pointer-to-function, which is "^?". if (Options.EncodeBlockParameters()) { const auto *FT = BT->getPointeeType()->castAs<FunctionType>(); S += '<'; // Block return type getObjCEncodingForTypeImpl(FT->getReturnType(), S, Options.forComponentType(), FD, NotEncodedT); // Block self S += "@?"; // Block parameters if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) { for (const auto &I : FPT->param_types()) getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD, NotEncodedT); } S += '>'; } return; } case Type::ObjCObject: { // hack to match legacy encoding of *id and *Class QualType Ty = getObjCObjectPointerType(CT); if (Ty->isObjCIdType()) { S += "{objc_object=}"; return; } else if (Ty->isObjCClassType()) { S += "{objc_class=}"; return; } // TODO: Double check to make sure this intentionally falls through. LLVM_FALLTHROUGH; } case Type::ObjCInterface: { // Ignore protocol qualifiers when mangling at this level. // @encode(class_name) ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface(); S += '{'; S += OI->getObjCRuntimeNameAsString(); if (Options.ExpandStructures()) { S += '='; SmallVector<const ObjCIvarDecl*, 32> Ivars; DeepCollectObjCIvars(OI, true, Ivars); for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { const FieldDecl *Field = Ivars[i]; if (Field->isBitField()) getObjCEncodingForTypeImpl(Field->getType(), S, ObjCEncOptions().setExpandStructures(), Field); else getObjCEncodingForTypeImpl(Field->getType(), S, ObjCEncOptions().setExpandStructures(), FD, NotEncodedT); } } S += '}'; return; } case Type::ObjCObjectPointer: { const auto *OPT = T->castAs<ObjCObjectPointerType>(); if (OPT->isObjCIdType()) { S += '@'; return; } if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { // FIXME: Consider if we need to output qualifiers for 'Class<p>'. // Since this is a binary compatibility issue, need to consult with // runtime folks. Fortunately, this is a *very* obscure construct. S += '#'; return; } if (OPT->isObjCQualifiedIdType()) { getObjCEncodingForTypeImpl( getObjCIdType(), S, Options.keepingOnly(ObjCEncOptions() .setExpandPointedToStructures() .setExpandStructures()), FD); if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) { // Note that we do extended encoding of protocol qualifer list // Only when doing ivar or property encoding. S += '"'; for (const auto *I : OPT->quals()) { S += '<'; S += I->getObjCRuntimeNameAsString(); S += '>'; } S += '"'; } return; } S += '@'; if (OPT->getInterfaceDecl() && (FD || Options.EncodingProperty() || Options.EncodeClassNames())) { S += '"'; S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); for (const auto *I : OPT->quals()) { S += '<'; S += I->getObjCRuntimeNameAsString(); S += '>'; } S += '"'; } return; } // gcc just blithely ignores member pointers. // FIXME: we should do better than that. 'M' is available. case Type::MemberPointer: // This matches gcc's encoding, even though technically it is insufficient. //FIXME. We should do a better job than gcc. case Type::Vector: case Type::ExtVector: // Until we have a coherent encoding of these three types, issue warning. if (NotEncodedT) *NotEncodedT = T; return; // We could see an undeduced auto type here during error recovery. // Just ignore it. case Type::Auto: case Type::DeducedTemplateSpecialization: return; case Type::Pipe: #define ABSTRACT_TYPE(KIND, BASE) #define TYPE(KIND, BASE) #define DEPENDENT_TYPE(KIND, BASE) \ case Type::KIND: #define NON_CANONICAL_TYPE(KIND, BASE) \ case Type::KIND: #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ case Type::KIND: #include "clang/AST/TypeNodes.inc" llvm_unreachable("@encode for dependent type!"); } llvm_unreachable("bad type kind!"); } void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, std::string &S, const FieldDecl *FD, bool includeVBases, QualType *NotEncodedT) const { assert(RDecl && "Expected non-null RecordDecl"); assert(!RDecl->isUnion() && "Should not be called for unions"); if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) return; const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; const ASTRecordLayout &layout = getASTRecordLayout(RDecl); if (CXXRec) { for (const auto &BI : CXXRec->bases()) { if (!BI.isVirtual()) { CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); if (base->isEmpty()) continue; uint64_t offs = toBits(layout.getBaseClassOffset(base)); FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), std::make_pair(offs, base)); } } } unsigned i = 0; for (auto *Field : RDecl->fields()) { uint64_t offs = layout.getFieldOffset(i); FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), std::make_pair(offs, Field)); ++i; } if (CXXRec && includeVBases) { for (const auto &BI : CXXRec->vbases()) { CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); if (base->isEmpty()) continue; uint64_t offs = toBits(layout.getVBaseClassOffset(base)); if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), std::make_pair(offs, base)); } } CharUnits size; if (CXXRec) { size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); } else { size = layout.getSize(); } #ifndef NDEBUG uint64_t CurOffs = 0; #endif std::multimap<uint64_t, NamedDecl *>::iterator CurLayObj = FieldOrBaseOffsets.begin(); if (CXXRec && CXXRec->isDynamicClass() && (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { if (FD) { S += "\"_vptr$"; std::string recname = CXXRec->getNameAsString(); if (recname.empty()) recname = "?"; S += recname; S += '"'; } S += "^^?"; #ifndef NDEBUG CurOffs += getTypeSize(VoidPtrTy); #endif } if (!RDecl->hasFlexibleArrayMember()) { // Mark the end of the structure. uint64_t offs = toBits(size); FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), std::make_pair(offs, nullptr)); } for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { #ifndef NDEBUG assert(CurOffs <= CurLayObj->first); if (CurOffs < CurLayObj->first) { uint64_t padding = CurLayObj->first - CurOffs; // FIXME: There doesn't seem to be a way to indicate in the encoding that // packing/alignment of members is different that normal, in which case // the encoding will be out-of-sync with the real layout. // If the runtime switches to just consider the size of types without // taking into account alignment, we could make padding explicit in the // encoding (e.g. using arrays of chars). The encoding strings would be // longer then though. CurOffs += padding; } #endif NamedDecl *dcl = CurLayObj->second; if (!dcl) break; // reached end of structure. if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) { // We expand the bases without their virtual bases since those are going // in the initial structure. Note that this differs from gcc which // expands virtual bases each time one is encountered in the hierarchy, // making the encoding type bigger than it really is. getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, NotEncodedT); assert(!base->isEmpty()); #ifndef NDEBUG CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); #endif } else { const auto *field = cast<FieldDecl>(dcl); if (FD) { S += '"'; S += field->getNameAsString(); S += '"'; } if (field->isBitField()) { EncodeBitField(this, S, field->getType(), field); #ifndef NDEBUG CurOffs += field->getBitWidthValue(*this); #endif } else { QualType qt = field->getType(); getLegacyIntegralTypeEncoding(qt); getObjCEncodingForTypeImpl( qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(), FD, NotEncodedT); #ifndef NDEBUG CurOffs += getTypeSize(field->getType()); #endif } } } } void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string& S) const { if (QT & Decl::OBJC_TQ_In) S += 'n'; if (QT & Decl::OBJC_TQ_Inout) S += 'N'; if (QT & Decl::OBJC_TQ_Out) S += 'o'; if (QT & Decl::OBJC_TQ_Bycopy) S += 'O'; if (QT & Decl::OBJC_TQ_Byref) S += 'R'; if (QT & Decl::OBJC_TQ_Oneway) S += 'V'; } TypedefDecl *ASTContext::getObjCIdDecl() const { if (!ObjCIdDecl) { QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {}); T = getObjCObjectPointerType(T); ObjCIdDecl = buildImplicitTypedef(T, "id"); } return ObjCIdDecl; } TypedefDecl *ASTContext::getObjCSelDecl() const { if (!ObjCSelDecl) { QualType T = getPointerType(ObjCBuiltinSelTy); ObjCSelDecl = buildImplicitTypedef(T, "SEL"); } return ObjCSelDecl; } TypedefDecl *ASTContext::getObjCClassDecl() const { if (!ObjCClassDecl) { QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {}); T = getObjCObjectPointerType(T); ObjCClassDecl = buildImplicitTypedef(T, "Class"); } return ObjCClassDecl; } ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { if (!ObjCProtocolClassDecl) { ObjCProtocolClassDecl = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), SourceLocation(), &Idents.get("Protocol"), /*typeParamList=*/nullptr, /*PrevDecl=*/nullptr, SourceLocation(), true); } return ObjCProtocolClassDecl; } //===----------------------------------------------------------------------===// // __builtin_va_list Construction Functions //===----------------------------------------------------------------------===// static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, StringRef Name) { // typedef char* __builtin[_ms]_va_list; QualType T = Context->getPointerType(Context->CharTy); return Context->buildImplicitTypedef(T, Name); } static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); } static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); } static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { // typedef void* __builtin_va_list; QualType T = Context->getPointerType(Context->VoidTy); return Context->buildImplicitTypedef(T, "__builtin_va_list"); } static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { // struct __va_list RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); if (Context->getLangOpts().CPlusPlus) { // namespace std { struct __va_list { NamespaceDecl *NS; NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(), /*Inline*/ false, SourceLocation(), SourceLocation(), &Context->Idents.get("std"), /*PrevDecl*/ nullptr); NS->setImplicit(); VaListTagDecl->setDeclContext(NS); } VaListTagDecl->startDefinition(); const size_t NumFields = 5; QualType FieldTypes[NumFields]; const char *FieldNames[NumFields]; // void *__stack; FieldTypes[0] = Context->getPointerType(Context->VoidTy); FieldNames[0] = "__stack"; // void *__gr_top; FieldTypes[1] = Context->getPointerType(Context->VoidTy); FieldNames[1] = "__gr_top"; // void *__vr_top; FieldTypes[2] = Context->getPointerType(Context->VoidTy); FieldNames[2] = "__vr_top"; // int __gr_offs; FieldTypes[3] = Context->IntTy; FieldNames[3] = "__gr_offs"; // int __vr_offs; FieldTypes[4] = Context->IntTy; FieldNames[4] = "__vr_offs"; // Create fields for (unsigned i = 0; i < NumFields; ++i) { FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); VaListTagDecl->addDecl(Field); } VaListTagDecl->completeDefinition(); Context->VaListTagDecl = VaListTagDecl; QualType VaListTagType = Context->getRecordType(VaListTagDecl); // } __builtin_va_list; return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); } static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { // typedef struct __va_list_tag { RecordDecl *VaListTagDecl; VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); VaListTagDecl->startDefinition(); const size_t NumFields = 5; QualType FieldTypes[NumFields]; const char *FieldNames[NumFields]; // unsigned char gpr; FieldTypes[0] = Context->UnsignedCharTy; FieldNames[0] = "gpr"; // unsigned char fpr; FieldTypes[1] = Context->UnsignedCharTy; FieldNames[1] = "fpr"; // unsigned short reserved; FieldTypes[2] = Context->UnsignedShortTy; FieldNames[2] = "reserved"; // void* overflow_arg_area; FieldTypes[3] = Context->getPointerType(Context->VoidTy); FieldNames[3] = "overflow_arg_area"; // void* reg_save_area; FieldTypes[4] = Context->getPointerType(Context->VoidTy); FieldNames[4] = "reg_save_area"; // Create fields for (unsigned i = 0; i < NumFields; ++i) { FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); VaListTagDecl->addDecl(Field); } VaListTagDecl->completeDefinition(); Context->VaListTagDecl = VaListTagDecl; QualType VaListTagType = Context->getRecordType(VaListTagDecl); // } __va_list_tag; TypedefDecl *VaListTagTypedefDecl = Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl); // typedef __va_list_tag __builtin_va_list[1]; llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); QualType VaListTagArrayType = Context->getConstantArrayType(VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0); return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); } static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { // struct __va_list_tag { RecordDecl *VaListTagDecl; VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); VaListTagDecl->startDefinition(); const size_t NumFields = 4; QualType FieldTypes[NumFields]; const char *FieldNames[NumFields]; // unsigned gp_offset; FieldTypes[0] = Context->UnsignedIntTy; FieldNames[0] = "gp_offset"; // unsigned fp_offset; FieldTypes[1] = Context->UnsignedIntTy; FieldNames[1] = "fp_offset"; // void* overflow_arg_area; FieldTypes[2] = Context->getPointerType(Context->VoidTy); FieldNames[2] = "overflow_arg_area"; // void* reg_save_area; FieldTypes[3] = Context->getPointerType(Context->VoidTy); FieldNames[3] = "reg_save_area"; // Create fields for (unsigned i = 0; i < NumFields; ++i) { FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); VaListTagDecl->addDecl(Field); } VaListTagDecl->completeDefinition(); Context->VaListTagDecl = VaListTagDecl; QualType VaListTagType = Context->getRecordType(VaListTagDecl); // }; // typedef struct __va_list_tag __builtin_va_list[1]; llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); QualType VaListTagArrayType = Context->getConstantArrayType( VaListTagType, Size, nullptr, ArrayType::Normal, 0); return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); } static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { // typedef int __builtin_va_list[4]; llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); QualType IntArrayType = Context->getConstantArrayType( Context->IntTy, Size, nullptr, ArrayType::Normal, 0); return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); } static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { // struct __va_list RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); if (Context->getLangOpts().CPlusPlus) { // namespace std { struct __va_list { NamespaceDecl *NS; NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(), /*Inline*/false, SourceLocation(), SourceLocation(), &Context->Idents.get("std"), /*PrevDecl*/ nullptr); NS->setImplicit(); VaListDecl->setDeclContext(NS); } VaListDecl->startDefinition(); // void * __ap; FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), VaListDecl, SourceLocation(), SourceLocation(), &Context->Idents.get("__ap"), Context->getPointerType(Context->VoidTy), /*TInfo=*/nullptr, /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); VaListDecl->addDecl(Field); // }; VaListDecl->completeDefinition(); Context->VaListTagDecl = VaListDecl; // typedef struct __va_list __builtin_va_list; QualType T = Context->getRecordType(VaListDecl); return Context->buildImplicitTypedef(T, "__builtin_va_list"); } static TypedefDecl * CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { // struct __va_list_tag { RecordDecl *VaListTagDecl; VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); VaListTagDecl->startDefinition(); const size_t NumFields = 4; QualType FieldTypes[NumFields]; const char *FieldNames[NumFields]; // long __gpr; FieldTypes[0] = Context->LongTy; FieldNames[0] = "__gpr"; // long __fpr; FieldTypes[1] = Context->LongTy; FieldNames[1] = "__fpr"; // void *__overflow_arg_area; FieldTypes[2] = Context->getPointerType(Context->VoidTy); FieldNames[2] = "__overflow_arg_area"; // void *__reg_save_area; FieldTypes[3] = Context->getPointerType(Context->VoidTy); FieldNames[3] = "__reg_save_area"; // Create fields for (unsigned i = 0; i < NumFields; ++i) { FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); VaListTagDecl->addDecl(Field); } VaListTagDecl->completeDefinition(); Context->VaListTagDecl = VaListTagDecl; QualType VaListTagType = Context->getRecordType(VaListTagDecl); // }; // typedef __va_list_tag __builtin_va_list[1]; llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); QualType VaListTagArrayType = Context->getConstantArrayType( VaListTagType, Size, nullptr, ArrayType::Normal, 0); return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); } static TypedefDecl *CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind) { switch (Kind) { case TargetInfo::CharPtrBuiltinVaList: return CreateCharPtrBuiltinVaListDecl(Context); case TargetInfo::VoidPtrBuiltinVaList: return CreateVoidPtrBuiltinVaListDecl(Context); case TargetInfo::AArch64ABIBuiltinVaList: return CreateAArch64ABIBuiltinVaListDecl(Context); case TargetInfo::PowerABIBuiltinVaList: return CreatePowerABIBuiltinVaListDecl(Context); case TargetInfo::X86_64ABIBuiltinVaList: return CreateX86_64ABIBuiltinVaListDecl(Context); case TargetInfo::PNaClABIBuiltinVaList: return CreatePNaClABIBuiltinVaListDecl(Context); case TargetInfo::AAPCSABIBuiltinVaList: return CreateAAPCSABIBuiltinVaListDecl(Context); case TargetInfo::SystemZBuiltinVaList: return CreateSystemZBuiltinVaListDecl(Context); } llvm_unreachable("Unhandled __builtin_va_list type kind"); } TypedefDecl *ASTContext::getBuiltinVaListDecl() const { if (!BuiltinVaListDecl) { BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); assert(BuiltinVaListDecl->isImplicit()); } return BuiltinVaListDecl; } Decl *ASTContext::getVaListTagDecl() const { // Force the creation of VaListTagDecl by building the __builtin_va_list // declaration. if (!VaListTagDecl) (void)getBuiltinVaListDecl(); return VaListTagDecl; } TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const { if (!BuiltinMSVaListDecl) BuiltinMSVaListDecl = CreateMSVaListDecl(this); return BuiltinMSVaListDecl; } bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const { return BuiltinInfo.canBeRedeclared(FD->getBuiltinID()); } void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { assert(ObjCConstantStringType.isNull() && "'NSConstantString' type already set!"); ObjCConstantStringType = getObjCInterfaceType(Decl); } /// Retrieve the template name that corresponds to a non-empty /// lookup. TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const { unsigned size = End - Begin; assert(size > 1 && "set is not overloaded!"); void *memory = Allocate(sizeof(OverloadedTemplateStorage) + size * sizeof(FunctionTemplateDecl*)); auto *OT = new (memory) OverloadedTemplateStorage(size); NamedDecl **Storage = OT->getStorage(); for (UnresolvedSetIterator I = Begin; I != End; ++I) { NamedDecl *D = *I; assert(isa<FunctionTemplateDecl>(D) || isa<UnresolvedUsingValueDecl>(D) || (isa<UsingShadowDecl>(D) && isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); *Storage++ = D; } return TemplateName(OT); } /// Retrieve a template name representing an unqualified-id that has been /// assumed to name a template for ADL purposes. TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const { auto *OT = new (*this) AssumedTemplateStorage(Name); return TemplateName(OT); } /// Retrieve the template name that represents a qualified /// template name such as \c std::vector. TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateDecl *Template) const { assert(NNS && "Missing nested-name-specifier in qualified template name"); // FIXME: Canonicalization? llvm::FoldingSetNodeID ID; QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); void *InsertPos = nullptr; QualifiedTemplateName *QTN = QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); if (!QTN) { QTN = new (*this, alignof(QualifiedTemplateName)) QualifiedTemplateName(NNS, TemplateKeyword, Template); QualifiedTemplateNames.InsertNode(QTN, InsertPos); } return TemplateName(QTN); } /// Retrieve the template name that represents a dependent /// template name such as \c MetaFun::template apply. TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) const { assert((!NNS || NNS->isDependent()) && "Nested name specifier must be dependent"); llvm::FoldingSetNodeID ID; DependentTemplateName::Profile(ID, NNS, Name); void *InsertPos = nullptr; DependentTemplateName *QTN = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); if (QTN) return TemplateName(QTN); NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); if (CanonNNS == NNS) { QTN = new (*this, alignof(DependentTemplateName)) DependentTemplateName(NNS, Name); } else { TemplateName Canon = getDependentTemplateName(CanonNNS, Name); QTN = new (*this, alignof(DependentTemplateName)) DependentTemplateName(NNS, Name, Canon); DependentTemplateName *CheckQTN = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); assert(!CheckQTN && "Dependent type name canonicalization broken"); (void)CheckQTN; } DependentTemplateNames.InsertNode(QTN, InsertPos); return TemplateName(QTN); } /// Retrieve the template name that represents a dependent /// template name such as \c MetaFun::template operator+. TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, OverloadedOperatorKind Operator) const { assert((!NNS || NNS->isDependent()) && "Nested name specifier must be dependent"); llvm::FoldingSetNodeID ID; DependentTemplateName::Profile(ID, NNS, Operator); void *InsertPos = nullptr; DependentTemplateName *QTN = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); if (QTN) return TemplateName(QTN); NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); if (CanonNNS == NNS) { QTN = new (*this, alignof(DependentTemplateName)) DependentTemplateName(NNS, Operator); } else { TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); QTN = new (*this, alignof(DependentTemplateName)) DependentTemplateName(NNS, Operator, Canon); DependentTemplateName *CheckQTN = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); assert(!CheckQTN && "Dependent template name canonicalization broken"); (void)CheckQTN; } DependentTemplateNames.InsertNode(QTN, InsertPos); return TemplateName(QTN); } TemplateName ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, TemplateName replacement) const { llvm::FoldingSetNodeID ID; SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); void *insertPos = nullptr; SubstTemplateTemplateParmStorage *subst = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); if (!subst) { subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); SubstTemplateTemplateParms.InsertNode(subst, insertPos); } return TemplateName(subst); } TemplateName ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, const TemplateArgument &ArgPack) const { auto &Self = const_cast<ASTContext &>(*this); llvm::FoldingSetNodeID ID; SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); void *InsertPos = nullptr; SubstTemplateTemplateParmPackStorage *Subst = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); if (!Subst) { Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, ArgPack.pack_size(), ArgPack.pack_begin()); SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); } return TemplateName(Subst); } /// getFromTargetType - Given one of the integer types provided by /// TargetInfo, produce the corresponding type. The unsigned @p Type /// is actually a value of type @c TargetInfo::IntType. CanQualType ASTContext::getFromTargetType(unsigned Type) const { switch (Type) { case TargetInfo::NoInt: return {}; case TargetInfo::SignedChar: return SignedCharTy; case TargetInfo::UnsignedChar: return UnsignedCharTy; case TargetInfo::SignedShort: return ShortTy; case TargetInfo::UnsignedShort: return UnsignedShortTy; case TargetInfo::SignedInt: return IntTy; case TargetInfo::UnsignedInt: return UnsignedIntTy; case TargetInfo::SignedLong: return LongTy; case TargetInfo::UnsignedLong: return UnsignedLongTy; case TargetInfo::SignedLongLong: return LongLongTy; case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; } llvm_unreachable("Unhandled TargetInfo::IntType value"); } //===----------------------------------------------------------------------===// // Type Predicates. //===----------------------------------------------------------------------===// /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's /// garbage collection attribute. /// Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { if (getLangOpts().getGC() == LangOptions::NonGC) return Qualifiers::GCNone; assert(getLangOpts().ObjC); Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); // Default behaviour under objective-C's gc is for ObjC pointers // (or pointers to them) be treated as though they were declared // as __strong. if (GCAttrs == Qualifiers::GCNone) { if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) return Qualifiers::Strong; else if (Ty->isPointerType()) return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType()); } else { // It's not valid to set GC attributes on anything that isn't a // pointer. #ifndef NDEBUG QualType CT = Ty->getCanonicalTypeInternal(); while (const auto *AT = dyn_cast<ArrayType>(CT)) CT = AT->getElementType(); assert(CT->isAnyPointerType() || CT->isBlockPointerType()); #endif } return GCAttrs; } //===----------------------------------------------------------------------===// // Type Compatibility Testing //===----------------------------------------------------------------------===// /// areCompatVectorTypes - Return true if the two specified vector types are /// compatible. static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS) { assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); return LHS->getElementType() == RHS->getElementType() && LHS->getNumElements() == RHS->getNumElements(); } bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec) { assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); if (hasSameUnqualifiedType(FirstVec, SecondVec)) return true; // Treat Neon vector types and most AltiVec vector types as if they are the // equivalent GCC vector types. const auto *First = FirstVec->castAs<VectorType>(); const auto *Second = SecondVec->castAs<VectorType>(); if (First->getNumElements() == Second->getNumElements() && hasSameType(First->getElementType(), Second->getElementType()) && First->getVectorKind() != VectorType::AltiVecPixel && First->getVectorKind() != VectorType::AltiVecBool && Second->getVectorKind() != VectorType::AltiVecPixel && Second->getVectorKind() != VectorType::AltiVecBool) return true; return false; } bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const { while (true) { // __strong id if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) { if (Attr->getAttrKind() == attr::ObjCOwnership) return true; Ty = Attr->getModifiedType(); // X *__strong (...) } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) { Ty = Paren->getInnerType(); // We do not want to look through typedefs, typeof(expr), // typeof(type), or any other way that the type is somehow // abstracted. } else { return false; } } } //===----------------------------------------------------------------------===// // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. //===----------------------------------------------------------------------===// /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the /// inheritance hierarchy of 'rProto'. bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const { if (declaresSameEntity(lProto, rProto)) return true; for (auto *PI : rProto->protocols()) if (ProtocolCompatibleWithProtocol(lProto, PI)) return true; return false; } /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and /// Class<pr1, ...>. bool ASTContext::ObjCQualifiedClassTypesAreCompatible( const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) { for (auto *lhsProto : lhs->quals()) { bool match = false; for (auto *rhsProto : rhs->quals()) { if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { match = true; break; } } if (!match) return false; } return true; } /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an /// ObjCQualifiedIDType. bool ASTContext::ObjCQualifiedIdTypesAreCompatible( const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs, bool compare) { // Allow id<P..> and an 'id' in all cases. if (lhs->isObjCIdType() || rhs->isObjCIdType()) return true; // Don't allow id<P..> to convert to Class or Class<P..> in either direction. if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() || rhs->isObjCClassType() || rhs->isObjCQualifiedClassType()) return false; if (lhs->isObjCQualifiedIdType()) { if (rhs->qual_empty()) { // If the RHS is a unqualified interface pointer "NSString*", // make sure we check the class hierarchy. if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { for (auto *I : lhs->quals()) { // when comparing an id<P> on lhs with a static type on rhs, // see if static class implements all of id's protocols, directly or // through its super class and categories. if (!rhsID->ClassImplementsProtocol(I, true)) return false; } } // If there are no qualifiers and no interface, we have an 'id'. return true; } // Both the right and left sides have qualifiers. for (auto *lhsProto : lhs->quals()) { bool match = false; // when comparing an id<P> on lhs with a static type on rhs, // see if static class implements all of id's protocols, directly or // through its super class and categories. for (auto *rhsProto : rhs->quals()) { if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { match = true; break; } } // If the RHS is a qualified interface pointer "NSString<P>*", // make sure we check the class hierarchy. if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) { for (auto *I : lhs->quals()) { // when comparing an id<P> on lhs with a static type on rhs, // see if static class implements all of id's protocols, directly or // through its super class and categories. if (rhsID->ClassImplementsProtocol(I, true)) { match = true; break; } } } if (!match) return false; } return true; } assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>"); if (lhs->getInterfaceType()) { // If both the right and left sides have qualifiers. for (auto *lhsProto : lhs->quals()) { bool match = false; // when comparing an id<P> on rhs with a static type on lhs, // see if static class implements all of id's protocols, directly or // through its super class and categories. // First, lhs protocols in the qualifier list must be found, direct // or indirect in rhs's qualifier list or it is a mismatch. for (auto *rhsProto : rhs->quals()) { if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { match = true; break; } } if (!match) return false; } // Static class's protocols, or its super class or category protocols // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) { llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; CollectInheritedProtocols(lhsID, LHSInheritedProtocols); // This is rather dubious but matches gcc's behavior. If lhs has // no type qualifier and its class has no static protocol(s) // assume that it is mismatch. if (LHSInheritedProtocols.empty() && lhs->qual_empty()) return false; for (auto *lhsProto : LHSInheritedProtocols) { bool match = false; for (auto *rhsProto : rhs->quals()) { if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { match = true; break; } } if (!match) return false; } } return true; } return false; } /// canAssignObjCInterfaces - Return true if the two interface types are /// compatible for assignment from RHS to LHS. This handles validation of any /// protocol qualifiers on the LHS or RHS. bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT) { const ObjCObjectType* LHS = LHSOPT->getObjectType(); const ObjCObjectType* RHS = RHSOPT->getObjectType(); // If either type represents the built-in 'id' type, return true. if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId()) return true; // Function object that propagates a successful result or handles // __kindof types. auto finish = [&](bool succeeded) -> bool { if (succeeded) return true; if (!RHS->isKindOfType()) return false; // Strip off __kindof and protocol qualifiers, then check whether // we can assign the other way. return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this), LHSOPT->stripObjCKindOfTypeAndQuals(*this)); }; // Casts from or to id<P> are allowed when the other side has compatible // protocols. if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) { return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false)); } // Verify protocol compatibility for casts from Class<P1> to Class<P2>. if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT)); } // Casts from Class to Class<Foo>, or vice-versa, are allowed. if (LHS->isObjCClass() && RHS->isObjCClass()) { return true; } // If we have 2 user-defined types, fall into that path. if (LHS->getInterface() && RHS->getInterface()) { return finish(canAssignObjCInterfaces(LHS, RHS)); } return false; } /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written /// for providing type-safety for objective-c pointers used to pass/return /// arguments in block literals. When passed as arguments, passing 'A*' where /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is /// not OK. For the return type, the opposite is not OK. bool ASTContext::canAssignObjCInterfacesInBlockPointer( const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType) { // Function object that propagates a successful result or handles // __kindof types. auto finish = [&](bool succeeded) -> bool { if (succeeded) return true; const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT; if (!Expected->isKindOfType()) return false; // Strip off __kindof and protocol qualifiers, then check whether // we can assign the other way. return canAssignObjCInterfacesInBlockPointer( RHSOPT->stripObjCKindOfTypeAndQuals(*this), LHSOPT->stripObjCKindOfTypeAndQuals(*this), BlockReturnType); }; if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) return true; if (LHSOPT->isObjCBuiltinType()) { return finish(RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType()); } if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) return finish(ObjCQualifiedIdTypesAreCompatible( (BlockReturnType ? LHSOPT : RHSOPT), (BlockReturnType ? RHSOPT : LHSOPT), false)); const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); if (LHS && RHS) { // We have 2 user-defined types. if (LHS != RHS) { if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) return finish(BlockReturnType); if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) return finish(!BlockReturnType); } else return true; } return false; } /// Comparison routine for Objective-C protocols to be used with /// llvm::array_pod_sort. static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, ObjCProtocolDecl * const *rhs) { return (*lhs)->getName().compare((*rhs)->getName()); } /// getIntersectionOfProtocols - This routine finds the intersection of set /// of protocols inherited from two distinct objective-c pointer objects with /// the given common base. /// It is used to build composite qualifier list of the composite type of /// the conditional expression involving two objective-c pointer objects. static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { const ObjCObjectType* LHS = LHSOPT->getObjectType(); const ObjCObjectType* RHS = RHSOPT->getObjectType(); assert(LHS->getInterface() && "LHS must have an interface base"); assert(RHS->getInterface() && "RHS must have an interface base"); // Add all of the protocols for the LHS. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet; // Start with the protocol qualifiers. for (auto proto : LHS->quals()) { Context.CollectInheritedProtocols(proto, LHSProtocolSet); } // Also add the protocols associated with the LHS interface. Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet); // Add all of the protocols for the RHS. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet; // Start with the protocol qualifiers. for (auto proto : RHS->quals()) { Context.CollectInheritedProtocols(proto, RHSProtocolSet); } // Also add the protocols associated with the RHS interface. Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet); // Compute the intersection of the collected protocol sets. for (auto proto : LHSProtocolSet) { if (RHSProtocolSet.count(proto)) IntersectionSet.push_back(proto); } // Compute the set of protocols that is implied by either the common type or // the protocols within the intersection. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols; Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols); // Remove any implied protocols from the list of inherited protocols. if (!ImpliedProtocols.empty()) { IntersectionSet.erase( std::remove_if(IntersectionSet.begin(), IntersectionSet.end(), [&](ObjCProtocolDecl *proto) -> bool { return ImpliedProtocols.count(proto) > 0; }), IntersectionSet.end()); } // Sort the remaining protocols by name. llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(), compareObjCProtocolsByName); } /// Determine whether the first type is a subtype of the second. static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, QualType rhs) { // Common case: two object pointers. const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>(); const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); if (lhsOPT && rhsOPT) return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); // Two block pointers. const auto *lhsBlock = lhs->getAs<BlockPointerType>(); const auto *rhsBlock = rhs->getAs<BlockPointerType>(); if (lhsBlock && rhsBlock) return ctx.typesAreBlockPointerCompatible(lhs, rhs); // If either is an unqualified 'id' and the other is a block, it's // acceptable. if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) || (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock)) return true; return false; } // Check that the given Objective-C type argument lists are equivalent. static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface, ArrayRef<QualType> lhsArgs, ArrayRef<QualType> rhsArgs, bool stripKindOf) { if (lhsArgs.size() != rhsArgs.size()) return false; ObjCTypeParamList *typeParams = iface->getTypeParamList(); for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) { if (ctx.hasSameType(lhsArgs[i], rhsArgs[i])) continue; switch (typeParams->begin()[i]->getVariance()) { case ObjCTypeParamVariance::Invariant: if (!stripKindOf || !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx), rhsArgs[i].stripObjCKindOfType(ctx))) { return false; } break; case ObjCTypeParamVariance::Covariant: if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i])) return false; break; case ObjCTypeParamVariance::Contravariant: if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i])) return false; break; } } return true; } QualType ASTContext::areCommonBaseCompatible( const ObjCObjectPointerType *Lptr, const ObjCObjectPointerType *Rptr) { const ObjCObjectType *LHS = Lptr->getObjectType(); const ObjCObjectType *RHS = Rptr->getObjectType(); const ObjCInterfaceDecl* LDecl = LHS->getInterface(); const ObjCInterfaceDecl* RDecl = RHS->getInterface(); if (!LDecl || !RDecl) return {}; // When either LHS or RHS is a kindof type, we should return a kindof type. // For example, for common base of kindof(ASub1) and kindof(ASub2), we return // kindof(A). bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType(); // Follow the left-hand side up the class hierarchy until we either hit a // root or find the RHS. Record the ancestors in case we don't find it. llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4> LHSAncestors; while (true) { // Record this ancestor. We'll need this if the common type isn't in the // path from the LHS to the root. LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS; if (declaresSameEntity(LHS->getInterface(), RDecl)) { // Get the type arguments. ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten(); bool anyChanges = false; if (LHS->isSpecialized() && RHS->isSpecialized()) { // Both have type arguments, compare them. if (!sameObjCTypeArgs(*this, LHS->getInterface(), LHS->getTypeArgs(), RHS->getTypeArgs(), /*stripKindOf=*/true)) return {}; } else if (LHS->isSpecialized() != RHS->isSpecialized()) { // If only one has type arguments, the result will not have type // arguments. LHSTypeArgs = {}; anyChanges = true; } // Compute the intersection of protocols. SmallVector<ObjCProtocolDecl *, 8> Protocols; getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr, Protocols); if (!Protocols.empty()) anyChanges = true; // If anything in the LHS will have changed, build a new result type. // If we need to return a kindof type but LHS is not a kindof type, we // build a new result type. if (anyChanges || LHS->isKindOfType() != anyKindOf) { QualType Result = getObjCInterfaceType(LHS->getInterface()); Result = getObjCObjectType(Result, LHSTypeArgs, Protocols, anyKindOf || LHS->isKindOfType()); return getObjCObjectPointerType(Result); } return getObjCObjectPointerType(QualType(LHS, 0)); } // Find the superclass. QualType LHSSuperType = LHS->getSuperClassType(); if (LHSSuperType.isNull()) break; LHS = LHSSuperType->castAs<ObjCObjectType>(); } // We didn't find anything by following the LHS to its root; now check // the RHS against the cached set of ancestors. while (true) { auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl()); if (KnownLHS != LHSAncestors.end()) { LHS = KnownLHS->second; // Get the type arguments. ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten(); bool anyChanges = false; if (LHS->isSpecialized() && RHS->isSpecialized()) { // Both have type arguments, compare them. if (!sameObjCTypeArgs(*this, LHS->getInterface(), LHS->getTypeArgs(), RHS->getTypeArgs(), /*stripKindOf=*/true)) return {}; } else if (LHS->isSpecialized() != RHS->isSpecialized()) { // If only one has type arguments, the result will not have type // arguments. RHSTypeArgs = {}; anyChanges = true; } // Compute the intersection of protocols. SmallVector<ObjCProtocolDecl *, 8> Protocols; getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr, Protocols); if (!Protocols.empty()) anyChanges = true; // If we need to return a kindof type but RHS is not a kindof type, we // build a new result type. if (anyChanges || RHS->isKindOfType() != anyKindOf) { QualType Result = getObjCInterfaceType(RHS->getInterface()); Result = getObjCObjectType(Result, RHSTypeArgs, Protocols, anyKindOf || RHS->isKindOfType()); return getObjCObjectPointerType(Result); } return getObjCObjectPointerType(QualType(RHS, 0)); } // Find the superclass of the RHS. QualType RHSSuperType = RHS->getSuperClassType(); if (RHSSuperType.isNull()) break; RHS = RHSSuperType->castAs<ObjCObjectType>(); } return {}; } bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, const ObjCObjectType *RHS) { assert(LHS->getInterface() && "LHS is not an interface type"); assert(RHS->getInterface() && "RHS is not an interface type"); // Verify that the base decls are compatible: the RHS must be a subclass of // the LHS. ObjCInterfaceDecl *LHSInterface = LHS->getInterface(); bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface()); if (!IsSuperClass) return false; // If the LHS has protocol qualifiers, determine whether all of them are // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the // LHS). if (LHS->getNumProtocols() > 0) { // OK if conversion of LHS to SuperClass results in narrowing of types // ; i.e., SuperClass may implement at least one of the protocols // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); // Also, if RHS has explicit quelifiers, include them for comparing with LHS's // qualifiers. for (auto *RHSPI : RHS->quals()) CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); // If there is no protocols associated with RHS, it is not a match. if (SuperClassInheritedProtocols.empty()) return false; for (const auto *LHSProto : LHS->quals()) { bool SuperImplementsProtocol = false; for (auto *SuperClassProto : SuperClassInheritedProtocols) if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { SuperImplementsProtocol = true; break; } if (!SuperImplementsProtocol) return false; } } // If the LHS is specialized, we may need to check type arguments. if (LHS->isSpecialized()) { // Follow the superclass chain until we've matched the LHS class in the // hierarchy. This substitutes type arguments through. const ObjCObjectType *RHSSuper = RHS; while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>(); // If the RHS is specializd, compare type arguments. if (RHSSuper->isSpecialized() && !sameObjCTypeArgs(*this, LHS->getInterface(), LHS->getTypeArgs(), RHSSuper->getTypeArgs(), /*stripKindOf=*/true)) { return false; } } return true; } bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { // get the "pointed to" types const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); if (!LHSOPT || !RHSOPT) return false; return canAssignObjCInterfaces(LHSOPT, RHSOPT) || canAssignObjCInterfaces(RHSOPT, LHSOPT); } bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { return canAssignObjCInterfaces( getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(), getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>()); } /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, /// both shall have the identically qualified version of a compatible type. /// C99 6.2.7p1: Two types have compatible types if their types are the /// same. See 6.7.[2,3,5] for additional rules. bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, bool CompareUnqualified) { if (getLangOpts().CPlusPlus) return hasSameType(LHS, RHS); return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); } bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { return typesAreCompatible(LHS, RHS); } bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { return !mergeTypes(LHS, RHS, true).isNull(); } /// mergeTransparentUnionType - if T is a transparent union type and a member /// of T is compatible with SubType, return the merged type, else return /// QualType() QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, bool OfBlockPointer, bool Unqualified) { if (const RecordType *UT = T->getAsUnionType()) { RecordDecl *UD = UT->getDecl(); if (UD->hasAttr<TransparentUnionAttr>()) { for (const auto *I : UD->fields()) { QualType ET = I->getType().getUnqualifiedType(); QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); if (!MT.isNull()) return MT; } } } return {}; } /// mergeFunctionParameterTypes - merge two types which appear as function /// parameter types QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, bool OfBlockPointer, bool Unqualified) { // GNU extension: two types are compatible if they appear as a function // argument, one of the types is a transparent union type and the other // type is compatible with a union member QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, Unqualified); if (!lmerge.isNull()) return lmerge; QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, Unqualified); if (!rmerge.isNull()) return rmerge; return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); } QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, bool OfBlockPointer, bool Unqualified) { const auto *lbase = lhs->castAs<FunctionType>(); const auto *rbase = rhs->castAs<FunctionType>(); const auto *lproto = dyn_cast<FunctionProtoType>(lbase); const auto *rproto = dyn_cast<FunctionProtoType>(rbase); bool allLTypes = true; bool allRTypes = true; // Check return type QualType retType; if (OfBlockPointer) { QualType RHS = rbase->getReturnType(); QualType LHS = lbase->getReturnType(); bool UnqualifiedResult = Unqualified; if (!UnqualifiedResult) UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); } else retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, Unqualified); if (retType.isNull()) return {}; if (Unqualified) retType = retType.getUnqualifiedType(); CanQualType LRetType = getCanonicalType(lbase->getReturnType()); CanQualType RRetType = getCanonicalType(rbase->getReturnType()); if (Unqualified) { LRetType = LRetType.getUnqualifiedType(); RRetType = RRetType.getUnqualifiedType(); } if (getCanonicalType(retType) != LRetType) allLTypes = false; if (getCanonicalType(retType) != RRetType) allRTypes = false; // FIXME: double check this // FIXME: should we error if lbase->getRegParmAttr() != 0 && // rbase->getRegParmAttr() != 0 && // lbase->getRegParmAttr() != rbase->getRegParmAttr()? FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); // Compatible functions must have compatible calling conventions if (lbaseInfo.getCC() != rbaseInfo.getCC()) return {}; // Regparm is part of the calling convention. if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) return {}; if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) return {}; if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) return {}; if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs()) return {}; if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck()) return {}; // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); if (lbaseInfo.getNoReturn() != NoReturn) allLTypes = false; if (rbaseInfo.getNoReturn() != NoReturn) allRTypes = false; FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); if (lproto && rproto) { // two C99 style function prototypes assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && "C++ shouldn't be here"); // Compatible functions must have the same number of parameters if (lproto->getNumParams() != rproto->getNumParams()) return {}; // Variadic and non-variadic functions aren't compatible if (lproto->isVariadic() != rproto->isVariadic()) return {}; if (lproto->getMethodQuals() != rproto->getMethodQuals()) return {}; SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos; bool canUseLeft, canUseRight; if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight, newParamInfos)) return {}; if (!canUseLeft) allLTypes = false; if (!canUseRight) allRTypes = false; // Check parameter type compatibility SmallVector<QualType, 10> types; for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); QualType paramType = mergeFunctionParameterTypes( lParamType, rParamType, OfBlockPointer, Unqualified); if (paramType.isNull()) return {}; if (Unqualified) paramType = paramType.getUnqualifiedType(); types.push_back(paramType); if (Unqualified) { lParamType = lParamType.getUnqualifiedType(); rParamType = rParamType.getUnqualifiedType(); } if (getCanonicalType(paramType) != getCanonicalType(lParamType)) allLTypes = false; if (getCanonicalType(paramType) != getCanonicalType(rParamType)) allRTypes = false; } if (allLTypes) return lhs; if (allRTypes) return rhs; FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); EPI.ExtInfo = einfo; EPI.ExtParameterInfos = newParamInfos.empty() ? nullptr : newParamInfos.data(); return getFunctionType(retType, types, EPI); } if (lproto) allRTypes = false; if (rproto) allLTypes = false; const FunctionProtoType *proto = lproto ? lproto : rproto; if (proto) { assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); if (proto->isVariadic()) return {}; // Check that the types are compatible with the types that // would result from default argument promotions (C99 6.7.5.3p15). // The only types actually affected are promotable integer // types and floats, which would be passed as a different // type depending on whether the prototype is visible. for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { QualType paramTy = proto->getParamType(i); // Look at the converted type of enum types, since that is the type used // to pass enum values. if (const auto *Enum = paramTy->getAs<EnumType>()) { paramTy = Enum->getDecl()->getIntegerType(); if (paramTy.isNull()) return {}; } if (paramTy->isPromotableIntegerType() || getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) return {}; } if (allLTypes) return lhs; if (allRTypes) return rhs; FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); EPI.ExtInfo = einfo; return getFunctionType(retType, proto->getParamTypes(), EPI); } if (allLTypes) return lhs; if (allRTypes) return rhs; return getFunctionNoProtoType(retType, einfo); } /// Given that we have an enum type and a non-enum type, try to merge them. static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, QualType other, bool isBlockReturnType) { // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, // a signed integer type, or an unsigned integer type. // Compatibility is based on the underlying type, not the promotion // type. QualType underlyingType = ET->getDecl()->getIntegerType(); if (underlyingType.isNull()) return {}; if (Context.hasSameType(underlyingType, other)) return other; // In block return types, we're more permissive and accept any // integral type of the same size. if (isBlockReturnType && other->isIntegerType() && Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) return other; return {}; } QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified, bool BlockReturnType) { // C++ [expr]: If an expression initially has the type "reference to T", the // type is adjusted to "T" prior to any further analysis, the expression // designates the object or function denoted by the reference, and the // expression is an lvalue unless the reference is an rvalue reference and // the expression is a function call (possibly inside parentheses). assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); if (Unqualified) { LHS = LHS.getUnqualifiedType(); RHS = RHS.getUnqualifiedType(); } QualType LHSCan = getCanonicalType(LHS), RHSCan = getCanonicalType(RHS); // If two types are identical, they are compatible. if (LHSCan == RHSCan) return LHS; // If the qualifiers are different, the types aren't compatible... mostly. Qualifiers LQuals = LHSCan.getLocalQualifiers(); Qualifiers RQuals = RHSCan.getLocalQualifiers(); if (LQuals != RQuals) { // If any of these qualifiers are different, we have a type // mismatch. if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || LQuals.getAddressSpace() != RQuals.getAddressSpace() || LQuals.getObjCLifetime() != RQuals.getObjCLifetime() || LQuals.hasUnaligned() != RQuals.hasUnaligned()) return {}; // Exactly one GC qualifier difference is allowed: __strong is // okay if the other type has no GC qualifier but is an Objective // C object pointer (i.e. implicitly strong by default). We fix // this by pretending that the unqualified type was actually // qualified __strong. Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) return {}; if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); } if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); } return {}; } // Okay, qualifiers are equal. Type::TypeClass LHSClass = LHSCan->getTypeClass(); Type::TypeClass RHSClass = RHSCan->getTypeClass(); // We want to consider the two function types to be the same for these // comparisons, just force one to the other. if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; // Same as above for arrays if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) LHSClass = Type::ConstantArray; if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) RHSClass = Type::ConstantArray; // ObjCInterfaces are just specialized ObjCObjects. if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; // Canonicalize ExtVector -> Vector. if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; // If the canonical type classes don't match. if (LHSClass != RHSClass) { // Note that we only have special rules for turning block enum // returns into block int returns, not vice-versa. if (const auto *ETy = LHS->getAs<EnumType>()) { return mergeEnumWithInteger(*this, ETy, RHS, false); } if (const EnumType* ETy = RHS->getAs<EnumType>()) { return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); } // allow block pointer type to match an 'id' type. if (OfBlockPointer && !BlockReturnType) { if (LHS->isObjCIdType() && RHS->isBlockPointerType()) return LHS; if (RHS->isObjCIdType() && LHS->isBlockPointerType()) return RHS; } return {}; } // The canonical type classes match. switch (LHSClass) { #define TYPE(Class, Base) #define ABSTRACT_TYPE(Class, Base) #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: #define DEPENDENT_TYPE(Class, Base) case Type::Class: #include "clang/AST/TypeNodes.inc" llvm_unreachable("Non-canonical and dependent types shouldn't get here"); case Type::Auto: case Type::DeducedTemplateSpecialization: case Type::LValueReference: case Type::RValueReference: case Type::MemberPointer: llvm_unreachable("C++ should never be in mergeTypes"); case Type::ObjCInterface: case Type::IncompleteArray: case Type::VariableArray: case Type::FunctionProto: case Type::ExtVector: llvm_unreachable("Types are eliminated above"); case Type::Pointer: { // Merge two pointer types, while trying to preserve typedef info QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType(); QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType(); if (Unqualified) { LHSPointee = LHSPointee.getUnqualifiedType(); RHSPointee = RHSPointee.getUnqualifiedType(); } QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, Unqualified); if (ResultType.isNull()) return {}; if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) return LHS; if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) return RHS; return getPointerType(ResultType); } case Type::BlockPointer: { // Merge two block pointer types, while trying to preserve typedef info QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType(); QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType(); if (Unqualified) { LHSPointee = LHSPointee.getUnqualifiedType(); RHSPointee = RHSPointee.getUnqualifiedType(); } if (getLangOpts().OpenCL) { Qualifiers LHSPteeQual = LHSPointee.getQualifiers(); Qualifiers RHSPteeQual = RHSPointee.getQualifiers(); // Blocks can't be an expression in a ternary operator (OpenCL v2.0 // 6.12.5) thus the following check is asymmetric. if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual)) return {}; LHSPteeQual.removeAddressSpace(); RHSPteeQual.removeAddressSpace(); LHSPointee = QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue()); RHSPointee = QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); } QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, Unqualified); if (ResultType.isNull()) return {}; if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) return LHS; if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) return RHS; return getBlockPointerType(ResultType); } case Type::Atomic: { // Merge two pointer types, while trying to preserve typedef info QualType LHSValue = LHS->castAs<AtomicType>()->getValueType(); QualType RHSValue = RHS->castAs<AtomicType>()->getValueType(); if (Unqualified) { LHSValue = LHSValue.getUnqualifiedType(); RHSValue = RHSValue.getUnqualifiedType(); } QualType ResultType = mergeTypes(LHSValue, RHSValue, false, Unqualified); if (ResultType.isNull()) return {}; if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) return LHS; if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) return RHS; return getAtomicType(ResultType); } case Type::ConstantArray: { const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) return {}; QualType LHSElem = getAsArrayType(LHS)->getElementType(); QualType RHSElem = getAsArrayType(RHS)->getElementType(); if (Unqualified) { LHSElem = LHSElem.getUnqualifiedType(); RHSElem = RHSElem.getUnqualifiedType(); } QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); if (ResultType.isNull()) return {}; const VariableArrayType* LVAT = getAsVariableArrayType(LHS); const VariableArrayType* RVAT = getAsVariableArrayType(RHS); // If either side is a variable array, and both are complete, check whether // the current dimension is definite. if (LVAT || RVAT) { auto SizeFetch = [this](const VariableArrayType* VAT, const ConstantArrayType* CAT) -> std::pair<bool,llvm::APInt> { if (VAT) { llvm::APSInt TheInt; Expr *E = VAT->getSizeExpr(); if (E && E->isIntegerConstantExpr(TheInt, *this)) return std::make_pair(true, TheInt); else return std::make_pair(false, TheInt); } else if (CAT) { return std::make_pair(true, CAT->getSize()); } else { return std::make_pair(false, llvm::APInt()); } }; bool HaveLSize, HaveRSize; llvm::APInt LSize, RSize; std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT); std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT); if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize)) return {}; // Definite, but unequal, array dimension } if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), LCAT->getSizeExpr(), ArrayType::ArraySizeModifier(), 0); if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), RCAT->getSizeExpr(), ArrayType::ArraySizeModifier(), 0); if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; if (LVAT) { // FIXME: This isn't correct! But tricky to implement because // the array's size has to be the size of LHS, but the type // has to be different. return LHS; } if (RVAT) { // FIXME: This isn't correct! But tricky to implement because // the array's size has to be the size of RHS, but the type // has to be different. return RHS; } if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(), 0); } case Type::FunctionNoProto: return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); case Type::Record: case Type::Enum: return {}; case Type::Builtin: // Only exactly equal builtin types are compatible, which is tested above. return {}; case Type::Complex: // Distinct complex types are incompatible. return {}; case Type::Vector: // FIXME: The merged type should be an ExtVector! if (areCompatVectorTypes(LHSCan->castAs<VectorType>(), RHSCan->castAs<VectorType>())) return LHS; return {}; case Type::ObjCObject: { // Check if the types are assignment compatible. // FIXME: This should be type compatibility, e.g. whether // "LHS x; RHS x;" at global scope is legal. if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(), RHS->castAs<ObjCObjectType>())) return LHS; return {}; } case Type::ObjCObjectPointer: if (OfBlockPointer) { if (canAssignObjCInterfacesInBlockPointer( LHS->castAs<ObjCObjectPointerType>(), RHS->castAs<ObjCObjectPointerType>(), BlockReturnType)) return LHS; return {}; } if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(), RHS->castAs<ObjCObjectPointerType>())) return LHS; return {}; case Type::Pipe: assert(LHS != RHS && "Equivalent pipe types should have already been handled!"); return {}; } llvm_unreachable("Invalid Type::Class!"); } bool ASTContext::mergeExtParameterInfo( const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) { assert(NewParamInfos.empty() && "param info list not empty"); CanUseFirst = CanUseSecond = true; bool FirstHasInfo = FirstFnType->hasExtParameterInfos(); bool SecondHasInfo = SecondFnType->hasExtParameterInfos(); // Fast path: if the first type doesn't have ext parameter infos, // we match if and only if the second type also doesn't have them. if (!FirstHasInfo && !SecondHasInfo) return true; bool NeedParamInfo = false; size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size() : SecondFnType->getExtParameterInfos().size(); for (size_t I = 0; I < E; ++I) { FunctionProtoType::ExtParameterInfo FirstParam, SecondParam; if (FirstHasInfo) FirstParam = FirstFnType->getExtParameterInfo(I); if (SecondHasInfo) SecondParam = SecondFnType->getExtParameterInfo(I); // Cannot merge unless everything except the noescape flag matches. if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false)) return false; bool FirstNoEscape = FirstParam.isNoEscape(); bool SecondNoEscape = SecondParam.isNoEscape(); bool IsNoEscape = FirstNoEscape && SecondNoEscape; NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape)); if (NewParamInfos.back().getOpaqueValue()) NeedParamInfo = true; if (FirstNoEscape != IsNoEscape) CanUseFirst = false; if (SecondNoEscape != IsNoEscape) CanUseSecond = false; } if (!NeedParamInfo) NewParamInfos.clear(); return true; } void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { ObjCLayouts[CD] = nullptr; } /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and /// 'RHS' attributes and returns the merged version; including for function /// return types. QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { QualType LHSCan = getCanonicalType(LHS), RHSCan = getCanonicalType(RHS); // If two types are identical, they are compatible. if (LHSCan == RHSCan) return LHS; if (RHSCan->isFunctionType()) { if (!LHSCan->isFunctionType()) return {}; QualType OldReturnType = cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); QualType NewReturnType = cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); QualType ResReturnType = mergeObjCGCQualifiers(NewReturnType, OldReturnType); if (ResReturnType.isNull()) return {}; if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); // In either case, use OldReturnType to build the new function type. const auto *F = LHS->castAs<FunctionType>(); if (const auto *FPT = cast<FunctionProtoType>(F)) { FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); EPI.ExtInfo = getFunctionExtInfo(LHS); QualType ResultType = getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); return ResultType; } } return {}; } // If the qualifiers are different, the types can still be merged. Qualifiers LQuals = LHSCan.getLocalQualifiers(); Qualifiers RQuals = RHSCan.getLocalQualifiers(); if (LQuals != RQuals) { // If any of these qualifiers are different, we have a type mismatch. if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || LQuals.getAddressSpace() != RQuals.getAddressSpace()) return {}; // Exactly one GC qualifier difference is allowed: __strong is // okay if the other type has no GC qualifier but is an Objective // C object pointer (i.e. implicitly strong by default). We fix // this by pretending that the unqualified type was actually // qualified __strong. Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) return {}; if (GC_L == Qualifiers::Strong) return LHS; if (GC_R == Qualifiers::Strong) return RHS; return {}; } if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType(); QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType(); QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); if (ResQT == LHSBaseQT) return LHS; if (ResQT == RHSBaseQT) return RHS; } return {}; } //===----------------------------------------------------------------------===// // Integer Predicates //===----------------------------------------------------------------------===// unsigned ASTContext::getIntWidth(QualType T) const { if (const auto *ET = T->getAs<EnumType>()) T = ET->getDecl()->getIntegerType(); if (T->isBooleanType()) return 1; // For builtin types, just use the standard type sizing method return (unsigned)getTypeSize(T); } QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && "Unexpected type"); // Turn <4 x signed int> -> <4 x unsigned int> if (const auto *VTy = T->getAs<VectorType>()) return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), VTy->getNumElements(), VTy->getVectorKind()); // For enums, we return the unsigned version of the base type. if (const auto *ETy = T->getAs<EnumType>()) T = ETy->getDecl()->getIntegerType(); switch (T->castAs<BuiltinType>()->getKind()) { case BuiltinType::Char_S: case BuiltinType::SChar: return UnsignedCharTy; case BuiltinType::Short: return UnsignedShortTy; case BuiltinType::Int: return UnsignedIntTy; case BuiltinType::Long: return UnsignedLongTy; case BuiltinType::LongLong: return UnsignedLongLongTy; case BuiltinType::Int128: return UnsignedInt128Ty; case BuiltinType::ShortAccum: return UnsignedShortAccumTy; case BuiltinType::Accum: return UnsignedAccumTy; case BuiltinType::LongAccum: return UnsignedLongAccumTy; case BuiltinType::SatShortAccum: return SatUnsignedShortAccumTy; case BuiltinType::SatAccum: return SatUnsignedAccumTy; case BuiltinType::SatLongAccum: return SatUnsignedLongAccumTy; case BuiltinType::ShortFract: return UnsignedShortFractTy; case BuiltinType::Fract: return UnsignedFractTy; case BuiltinType::LongFract: return UnsignedLongFractTy; case BuiltinType::SatShortFract: return SatUnsignedShortFractTy; case BuiltinType::SatFract: return SatUnsignedFractTy; case BuiltinType::SatLongFract: return SatUnsignedLongFractTy; default: llvm_unreachable("Unexpected signed integer or fixed point type"); } } ASTMutationListener::~ASTMutationListener() = default; void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {} //===----------------------------------------------------------------------===// // Builtin Type Computation //===----------------------------------------------------------------------===// /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the /// pointer over the consumed characters. This returns the resultant type. If /// AllowTypeModifiers is false then modifier like * are not parsed, just basic /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of /// a vector of "i*". /// /// RequiresICE is filled in on return to indicate whether the value is required /// to be an Integer Constant Expression. static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequiresICE, bool AllowTypeModifiers) { // Modifiers. int HowLong = 0; bool Signed = false, Unsigned = false; RequiresICE = false; // Read the prefixed modifiers first. bool Done = false; #ifndef NDEBUG bool IsSpecial = false; #endif while (!Done) { switch (*Str++) { default: Done = true; --Str; break; case 'I': RequiresICE = true; break; case 'S': assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); assert(!Signed && "Can't use 'S' modifier multiple times!"); Signed = true; break; case 'U': assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); assert(!Unsigned && "Can't use 'U' modifier multiple times!"); Unsigned = true; break; case 'L': assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers"); assert(HowLong <= 2 && "Can't have LLLL modifier"); ++HowLong; break; case 'N': // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); #ifndef NDEBUG IsSpecial = true; #endif if (Context.getTargetInfo().getLongWidth() == 32) ++HowLong; break; case 'W': // This modifier represents int64 type. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); #ifndef NDEBUG IsSpecial = true; #endif switch (Context.getTargetInfo().getInt64Type()) { default: llvm_unreachable("Unexpected integer type"); case TargetInfo::SignedLong: HowLong = 1; break; case TargetInfo::SignedLongLong: HowLong = 2; break; } break; case 'Z': // This modifier represents int32 type. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!"); #ifndef NDEBUG IsSpecial = true; #endif switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) { default: llvm_unreachable("Unexpected integer type"); case TargetInfo::SignedInt: HowLong = 0; break; case TargetInfo::SignedLong: HowLong = 1; break; case TargetInfo::SignedLongLong: HowLong = 2; break; } break; case 'O': assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!"); #ifndef NDEBUG IsSpecial = true; #endif if (Context.getLangOpts().OpenCL) HowLong = 1; else HowLong = 2; break; } } QualType Type; // Read the base type. switch (*Str++) { default: llvm_unreachable("Unknown builtin type letter!"); // Scaffold qbit type for builtin gates case 'l': assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers used with 'l'!"); Type = Context.CbitTy; break; case 'q': assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers used with 'q'!"); Type = Context.QbitTy; break; case 'y': assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers used with 'y'!"); Type = Context.QintTy; break; case 'v': assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers used with 'v'!"); Type = Context.VoidTy; break; case 'h': assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers used with 'h'!"); Type = Context.HalfTy; break; case 'f': assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers used with 'f'!"); Type = Context.FloatTy; break; case 'd': assert(HowLong < 3 && !Signed && !Unsigned && "Bad modifiers used with 'd'!"); if (HowLong == 1) Type = Context.LongDoubleTy; else if (HowLong == 2) Type = Context.Float128Ty; else Type = Context.DoubleTy; break; case 's': assert(HowLong == 0 && "Bad modifiers used with 's'!"); if (Unsigned) Type = Context.UnsignedShortTy; else Type = Context.ShortTy; break; case 'i': if (HowLong == 3) Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; else if (HowLong == 2) Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; else if (HowLong == 1) Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; else Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; break; case 'c': assert(HowLong == 0 && "Bad modifiers used with 'c'!"); if (Signed) Type = Context.SignedCharTy; else if (Unsigned) Type = Context.UnsignedCharTy; else Type = Context.CharTy; break; case 'b': // boolean assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); Type = Context.BoolTy; break; case 'z': // size_t. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); Type = Context.getSizeType(); break; case 'w': // wchar_t. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); Type = Context.getWideCharType(); break; case 'F': Type = Context.getCFConstantStringType(); break; case 'G': Type = Context.getObjCIdType(); break; case 'H': Type = Context.getObjCSelType(); break; case 'M': Type = Context.getObjCSuperType(); break; case 'a': Type = Context.getBuiltinVaListType(); assert(!Type.isNull() && "builtin va list type not initialized!"); break; case 'A': // This is a "reference" to a va_list; however, what exactly // this means depends on how va_list is defined. There are two // different kinds of va_list: ones passed by value, and ones // passed by reference. An example of a by-value va_list is // x86, where va_list is a char*. An example of by-ref va_list // is x86-64, where va_list is a __va_list_tag[1]. For x86, // we want this argument to be a char*&; for x86-64, we want // it to be a __va_list_tag*. Type = Context.getBuiltinVaListType(); assert(!Type.isNull() && "builtin va list type not initialized!"); if (Type->isArrayType()) Type = Context.getArrayDecayedType(Type); else Type = Context.getLValueReferenceType(Type); break; case 'V': { char *End; unsigned NumElements = strtoul(Str, &End, 10); assert(End != Str && "Missing vector size"); Str = End; QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, false); assert(!RequiresICE && "Can't require vector ICE"); // TODO: No way to make AltiVec vectors in builtins yet. Type = Context.getVectorType(ElementType, NumElements, VectorType::GenericVector); break; } case 'E': { char *End; unsigned NumElements = strtoul(Str, &End, 10); assert(End != Str && "Missing vector size"); Str = End; QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, false); Type = Context.getExtVectorType(ElementType, NumElements); break; } case 'X': { QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, false); assert(!RequiresICE && "Can't require complex ICE"); Type = Context.getComplexType(ElementType); break; } case 'Y': Type = Context.getPointerDiffType(); break; case 'P': Type = Context.getFILEType(); if (Type.isNull()) { Error = ASTContext::GE_Missing_stdio; return {}; } break; case 'J': if (Signed) Type = Context.getsigjmp_bufType(); else Type = Context.getjmp_bufType(); if (Type.isNull()) { Error = ASTContext::GE_Missing_setjmp; return {}; } break; case 'K': assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); Type = Context.getucontext_tType(); if (Type.isNull()) { Error = ASTContext::GE_Missing_ucontext; return {}; } break; case 'p': Type = Context.getProcessIDType(); break; } // If there are modifiers and if we're allowed to parse them, go for it. Done = !AllowTypeModifiers; while (!Done) { switch (char c = *Str++) { default: Done = true; --Str; break; case '*': case '&': { // Both pointers and references can have their pointee types // qualified with an address space. char *End; unsigned AddrSpace = strtoul(Str, &End, 10); if (End != Str) { // Note AddrSpace == 0 is not the same as an unspecified address space. Type = Context.getAddrSpaceQualType( Type, Context.getLangASForBuiltinAddressSpace(AddrSpace)); Str = End; } if (c == '*') Type = Context.getPointerType(Type); else Type = Context.getLValueReferenceType(Type); break; } // FIXME: There's no way to have a built-in with an rvalue ref arg. case 'C': Type = Type.withConst(); break; case 'D': Type = Context.getVolatileType(Type); break; case 'R': Type = Type.withRestrict(); break; } } assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && "Integer constant 'I' type must be an integer"); return Type; } /// GetBuiltinType - Return the type for the specified builtin. QualType ASTContext::GetBuiltinType(unsigned Id, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs) const { const char *TypeStr = BuiltinInfo.getTypeString(Id); if (TypeStr[0] == '\0') { Error = GE_Missing_type; return {}; } SmallVector<QualType, 8> ArgTypes; bool RequiresICE = false; Error = GE_None; QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); if (Error != GE_None) return {}; assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); while (TypeStr[0] && TypeStr[0] != '.') { QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); if (Error != GE_None) return {}; // If this argument is required to be an IntegerConstantExpression and the // caller cares, fill in the bitmask we return. if (RequiresICE && IntegerConstantArgs) *IntegerConstantArgs |= 1 << ArgTypes.size(); // Do array -> pointer decay. The builtin should use the decayed type. if (Ty->isArrayType()) Ty = getArrayDecayedType(Ty); ArgTypes.push_back(Ty); } if (Id == Builtin::BI__GetExceptionInfo) return {}; assert((TypeStr[0] != '.' || TypeStr[1] == 0) && "'.' should only occur at end of builtin type list!"); bool Variadic = (TypeStr[0] == '.'); FunctionType::ExtInfo EI(getDefaultCallingConvention( Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); // We really shouldn't be making a no-proto type here. if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus) return getFunctionNoProtoType(ResType, EI); FunctionProtoType::ExtProtoInfo EPI; EPI.ExtInfo = EI; EPI.Variadic = Variadic; if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id)) EPI.ExceptionSpec.Type = getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; return getFunctionType(ResType, ArgTypes, EPI); } static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, const FunctionDecl *FD) { if (!FD->isExternallyVisible()) return GVA_Internal; // Non-user-provided functions get emitted as weak definitions with every // use, no matter whether they've been explicitly instantiated etc. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) if (!MD->isUserProvided()) return GVA_DiscardableODR; GVALinkage External; switch (FD->getTemplateSpecializationKind()) { case TSK_Undeclared: case TSK_ExplicitSpecialization: External = GVA_StrongExternal; break; case TSK_ExplicitInstantiationDefinition: return GVA_StrongODR; // C++11 [temp.explicit]p10: // [ Note: The intent is that an inline function that is the subject of // an explicit instantiation declaration will still be implicitly // instantiated when used so that the body can be considered for // inlining, but that no out-of-line copy of the inline function would be // generated in the translation unit. -- end note ] case TSK_ExplicitInstantiationDeclaration: return GVA_AvailableExternally; case TSK_ImplicitInstantiation: External = GVA_DiscardableODR; break; } if (!FD->isInlined()) return External; if ((!Context.getLangOpts().CPlusPlus && !Context.getTargetInfo().getCXXABI().isMicrosoft() && !FD->hasAttr<DLLExportAttr>()) || FD->hasAttr<GNUInlineAttr>()) { // FIXME: This doesn't match gcc's behavior for dllexport inline functions. // GNU or C99 inline semantics. Determine whether this symbol should be // externally visible. if (FD->isInlineDefinitionExternallyVisible()) return External; // C99 inline semantics, where the symbol is not externally visible. return GVA_AvailableExternally; } // Functions specified with extern and inline in -fms-compatibility mode // forcibly get emitted. While the body of the function cannot be later // replaced, the function definition cannot be discarded. if (FD->isMSExternInline()) return GVA_StrongODR; return GVA_DiscardableODR; } static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L) { // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx // dllexport/dllimport on inline functions. if (D->hasAttr<DLLImportAttr>()) { if (L == GVA_DiscardableODR || L == GVA_StrongODR) return GVA_AvailableExternally; } else if (D->hasAttr<DLLExportAttr>()) { if (L == GVA_DiscardableODR) return GVA_StrongODR; } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice && D->hasAttr<CUDAGlobalAttr>()) { // Device-side functions with __global__ attribute must always be // visible externally so they can be launched from host. if (L == GVA_DiscardableODR || L == GVA_Internal) return GVA_StrongODR; } return L; } /// Adjust the GVALinkage for a declaration based on what an external AST source /// knows about whether there can be other definitions of this declaration. static GVALinkage adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, GVALinkage L) { ExternalASTSource *Source = Ctx.getExternalSource(); if (!Source) return L; switch (Source->hasExternalDefinitions(D)) { case ExternalASTSource::EK_Never: // Other translation units rely on us to provide the definition. if (L == GVA_DiscardableODR) return GVA_StrongODR; break; case ExternalASTSource::EK_Always: return GVA_AvailableExternally; case ExternalASTSource::EK_ReplyHazy: break; } return L; } GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { return adjustGVALinkageForExternalDefinitionKind(*this, FD, adjustGVALinkageForAttributes(*this, FD, basicGVALinkageForFunction(*this, FD))); } static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD) { if (!VD->isExternallyVisible()) return GVA_Internal; if (VD->isStaticLocal()) { const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); while (LexicalContext && !isa<FunctionDecl>(LexicalContext)) LexicalContext = LexicalContext->getLexicalParent(); // ObjC Blocks can create local variables that don't have a FunctionDecl // LexicalContext. if (!LexicalContext) return GVA_DiscardableODR; // Otherwise, let the static local variable inherit its linkage from the // nearest enclosing function. auto StaticLocalLinkage = Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext)); // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must // be emitted in any object with references to the symbol for the object it // contains, whether inline or out-of-line." // Similar behavior is observed with MSVC. An alternative ABI could use // StrongODR/AvailableExternally to match the function, but none are // known/supported currently. if (StaticLocalLinkage == GVA_StrongODR || StaticLocalLinkage == GVA_AvailableExternally) return GVA_DiscardableODR; return StaticLocalLinkage; } // MSVC treats in-class initialized static data members as definitions. // By giving them non-strong linkage, out-of-line definitions won't // cause link errors. if (Context.isMSStaticDataMemberInlineDefinition(VD)) return GVA_DiscardableODR; // Most non-template variables have strong linkage; inline variables are // linkonce_odr or (occasionally, for compatibility) weak_odr. GVALinkage StrongLinkage; switch (Context.getInlineVariableDefinitionKind(VD)) { case ASTContext::InlineVariableDefinitionKind::None: StrongLinkage = GVA_StrongExternal; break; case ASTContext::InlineVariableDefinitionKind::Weak: case ASTContext::InlineVariableDefinitionKind::WeakUnknown: StrongLinkage = GVA_DiscardableODR; break; case ASTContext::InlineVariableDefinitionKind::Strong: StrongLinkage = GVA_StrongODR; break; } switch (VD->getTemplateSpecializationKind()) { case TSK_Undeclared: return StrongLinkage; case TSK_ExplicitSpecialization: return Context.getTargetInfo().getCXXABI().isMicrosoft() && VD->isStaticDataMember() ? GVA_StrongODR : StrongLinkage; case TSK_ExplicitInstantiationDefinition: return GVA_StrongODR; case TSK_ExplicitInstantiationDeclaration: return GVA_AvailableExternally; case TSK_ImplicitInstantiation: return GVA_DiscardableODR; } llvm_unreachable("Invalid Linkage!"); } GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { return adjustGVALinkageForExternalDefinitionKind(*this, VD, adjustGVALinkageForAttributes(*this, VD, basicGVALinkageForVariable(*this, VD))); } bool ASTContext::DeclMustBeEmitted(const Decl *D) { if (const auto *VD = dyn_cast<VarDecl>(D)) { if (!VD->isFileVarDecl()) return false; // Global named register variables (GNU extension) are never emitted. if (VD->getStorageClass() == SC_Register) return false; if (VD->getDescribedVarTemplate() || isa<VarTemplatePartialSpecializationDecl>(VD)) return false; } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { // We never need to emit an uninstantiated function template. if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) return false; } else if (isa<PragmaCommentDecl>(D)) return true; else if (isa<PragmaDetectMismatchDecl>(D)) return true; else if (isa<OMPThreadPrivateDecl>(D)) return !D->getDeclContext()->isDependentContext(); else if (isa<OMPAllocateDecl>(D)) return !D->getDeclContext()->isDependentContext(); else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D)) return !D->getDeclContext()->isDependentContext(); else if (isa<ImportDecl>(D)) return true; else return false; if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) { assert(getExternalSource() && "It's from an AST file; must have a source."); // On Windows, PCH files are built together with an object file. If this // declaration comes from such a PCH and DeclMustBeEmitted would return // true, it would have returned true and the decl would have been emitted // into that object file, so it doesn't need to be emitted here. // Note that decls are still emitted if they're referenced, as usual; // DeclMustBeEmitted is used to decide whether a decl must be emitted even // if it's not referenced. // // Explicit template instantiation definitions are tricky. If there was an // explicit template instantiation decl in the PCH before, it will look like // the definition comes from there, even if that was just the declaration. // (Explicit instantiation defs of variable templates always get emitted.) bool IsExpInstDef = isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->getTemplateSpecializationKind() == TSK_ExplicitInstantiationDefinition; // Implicit member function definitions, such as operator= might not be // marked as template specializations, since they're not coming from a // template but synthesized directly on the class. IsExpInstDef |= isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() == TSK_ExplicitInstantiationDefinition; if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef) return false; } // If this is a member of a class template, we do not need to emit it. if (D->getDeclContext()->isDependentContext()) return false; // Weak references don't produce any output by themselves. if (D->hasAttr<WeakRefAttr>()) return false; // Aliases and used decls are required. if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) return true; if (const auto *FD = dyn_cast<FunctionDecl>(D)) { // Forward declarations aren't required. if (!FD->doesThisDeclarationHaveABody()) return FD->doesDeclarationForceExternallyVisibleDefinition(); // Constructors and destructors are required. if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) return true; // The key function for a class is required. This rule only comes // into play when inline functions can be key functions, though. if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { const CXXRecordDecl *RD = MD->getParent(); if (MD->isOutOfLine() && RD->isDynamicClass()) { const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) return true; } } } GVALinkage Linkage = GetGVALinkageForFunction(FD); // static, static inline, always_inline, and extern inline functions can // always be deferred. Normal inline functions can be deferred in C99/C++. // Implicit template instantiations can also be deferred in C++. return !isDiscardableGVALinkage(Linkage); } const auto *VD = cast<VarDecl>(D); assert(VD->isFileVarDecl() && "Expected file scoped var"); // If the decl is marked as `declare target to`, it should be emitted for the // host and for the device. if (LangOpts.OpenMP && OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) return true; if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly && !isMSStaticDataMemberInlineDefinition(VD)) return false; // Variables that can be needed in other TUs are required. auto Linkage = GetGVALinkageForVariable(VD); if (!isDiscardableGVALinkage(Linkage)) return true; // We never need to emit a variable that is available in another TU. if (Linkage == GVA_AvailableExternally) return false; // Variables that have destruction with side-effects are required. if (VD->needsDestruction(*this)) return true; // Variables that have initialization with side-effects are required. if (VD->getInit() && VD->getInit()->HasSideEffects(*this) && // We can get a value-dependent initializer during error recovery. (VD->getInit()->isValueDependent() || !VD->evaluateValue())) return true; // Likewise, variables with tuple-like bindings are required if their // bindings have side-effects. if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) for (const auto *BD : DD->bindings()) if (const auto *BindingVD = BD->getHoldingVar()) if (DeclMustBeEmitted(BindingVD)) return true; return false; } void ASTContext::forEachMultiversionedFunctionVersion( const FunctionDecl *FD, llvm::function_ref<void(FunctionDecl *)> Pred) const { assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls; FD = FD->getMostRecentDecl(); for (auto *CurDecl : FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) { FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl(); if (CurFD && hasSameType(CurFD->getType(), FD->getType()) && std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) { SeenDecls.insert(CurFD); Pred(CurFD); } } } CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin) const { // Pass through to the C++ ABI object if (IsCXXMethod) return ABI->getDefaultMethodCallConv(IsVariadic); // Builtins ignore user-specified default calling convention and remain the // Target's default calling convention. if (!IsBuiltin) { switch (LangOpts.getDefaultCallingConv()) { case LangOptions::DCC_None: break; case LangOptions::DCC_CDecl: return CC_C; case LangOptions::DCC_FastCall: if (getTargetInfo().hasFeature("sse2") && !IsVariadic) return CC_X86FastCall; break; case LangOptions::DCC_StdCall: if (!IsVariadic) return CC_X86StdCall; break; case LangOptions::DCC_VectorCall: // __vectorcall cannot be applied to variadic functions. if (!IsVariadic) return CC_X86VectorCall; break; case LangOptions::DCC_RegCall: // __regcall cannot be applied to variadic functions. if (!IsVariadic) return CC_X86RegCall; break; } } return Target->getDefaultCallingConv(); } bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { // Pass through to the C++ ABI object return ABI->isNearlyEmpty(RD); } VTableContextBase *ASTContext::getVTableContext() { if (!VTContext.get()) { if (Target->getCXXABI().isMicrosoft()) VTContext.reset(new MicrosoftVTableContext(*this)); else VTContext.reset(new ItaniumVTableContext(*this)); } return VTContext.get(); } MangleContext *ASTContext::createMangleContext(const TargetInfo *T) { if (!T) T = Target; switch (T->getCXXABI().getKind()) { case TargetCXXABI::Fuchsia: case TargetCXXABI::GenericAArch64: case TargetCXXABI::GenericItanium: case TargetCXXABI::GenericARM: case TargetCXXABI::GenericMIPS: case TargetCXXABI::iOS: case TargetCXXABI::iOS64: case TargetCXXABI::WebAssembly: case TargetCXXABI::WatchOS: return ItaniumMangleContext::create(*this, getDiagnostics()); case TargetCXXABI::Microsoft: return MicrosoftMangleContext::create(*this, getDiagnostics()); } llvm_unreachable("Unsupported ABI"); } CXXABI::~CXXABI() = default; size_t ASTContext::getSideTableAllocatedMemory() const { return ASTRecordLayouts.getMemorySize() + llvm::capacity_in_bytes(ObjCLayouts) + llvm::capacity_in_bytes(KeyFunctions) + llvm::capacity_in_bytes(ObjCImpls) + llvm::capacity_in_bytes(BlockVarCopyInits) + llvm::capacity_in_bytes(DeclAttrs) + llvm::capacity_in_bytes(TemplateOrInstantiation) + llvm::capacity_in_bytes(InstantiatedFromUsingDecl) + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) + llvm::capacity_in_bytes(OverriddenMethods) + llvm::capacity_in_bytes(Types) + llvm::capacity_in_bytes(VariableArrayTypes); } /// getIntTypeForBitwidth - /// sets integer QualTy according to specified details: /// bitwidth, signed/unsigned. /// Returns empty type if there is no appropriate target types. QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const { TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed); CanQualType QualTy = getFromTargetType(Ty); if (!QualTy && DestWidth == 128) return Signed ? Int128Ty : UnsignedInt128Ty; return QualTy; } /// getRealTypeForBitwidth - /// sets floating point QualTy according to specified bitwidth. /// Returns empty type if there is no appropriate target types. QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const { TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth); switch (Ty) { case TargetInfo::Float: return FloatTy; case TargetInfo::Double: return DoubleTy; case TargetInfo::LongDouble: return LongDoubleTy; case TargetInfo::Float128: return Float128Ty; case TargetInfo::NoFloat: return {}; } llvm_unreachable("Unhandled TargetInfo::RealType value"); } void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { if (Number > 1) MangleNumbers[ND] = Number; } unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const { auto I = MangleNumbers.find(ND); return I != MangleNumbers.end() ? I->second : 1; } void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { if (Number > 1) StaticLocalNumbers[VD] = Number; } unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { auto I = StaticLocalNumbers.find(VD); return I != StaticLocalNumbers.end() ? I->second : 1; } MangleNumberingContext & ASTContext::getManglingNumberContext(const DeclContext *DC) { assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC]; if (!MCtx) MCtx = createMangleNumberingContext(); return *MCtx; } MangleNumberingContext & ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) { assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. std::unique_ptr<MangleNumberingContext> &MCtx = ExtraMangleNumberingContexts[D]; if (!MCtx) MCtx = createMangleNumberingContext(); return *MCtx; } std::unique_ptr<MangleNumberingContext> ASTContext::createMangleNumberingContext() const { return ABI->createMangleNumberingContext(); } const CXXConstructorDecl * ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { return ABI->getCopyConstructorForExceptionObject( cast<CXXRecordDecl>(RD->getFirstDecl())); } void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD) { return ABI->addCopyConstructorForExceptionObject( cast<CXXRecordDecl>(RD->getFirstDecl()), cast<CXXConstructorDecl>(CD->getFirstDecl())); } void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *DD) { return ABI->addTypedefNameForUnnamedTagDecl(TD, DD); } TypedefNameDecl * ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { return ABI->getTypedefNameForUnnamedTagDecl(TD); } void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD) { return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); } DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { return ABI->getDeclaratorForUnnamedTagDecl(TD); } void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { ParamIndices[D] = index; } unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { ParameterIndexTable::const_iterator I = ParamIndices.find(D); assert(I != ParamIndices.end() && "ParmIndices lacks entry set by ParmVarDecl"); return I->second; } QualType ASTContext::getStringLiteralArrayType(QualType EltTy, unsigned Length) const { // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) EltTy = EltTy.withConst(); EltTy = adjustStringLiteralBaseType(EltTy); // Get an array type for the string, according to C99 6.4.5. This includes // the null terminator character. return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0); } StringLiteral * ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const { StringLiteral *&Result = StringLiteralCache[Key]; if (!Result) Result = StringLiteral::Create( *this, Key, StringLiteral::Ascii, /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()), SourceLocation()); return Result; } bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { const llvm::Triple &T = getTargetInfo().getTriple(); if (!T.isOSDarwin()) return false; if (!(T.isiOS() && T.isOSVersionLT(7)) && !(T.isMacOSX() && T.isOSVersionLT(10, 9))) return false; QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); CharUnits sizeChars = getTypeSizeInChars(AtomicTy); uint64_t Size = sizeChars.getQuantity(); CharUnits alignChars = getTypeAlignInChars(AtomicTy); unsigned Align = alignChars.getQuantity(); unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth(); return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); } /// Template specializations to abstract away from pointers and TypeLocs. /// @{ template <typename T> static ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) { return ast_type_traits::DynTypedNode::create(*Node); } template <> ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) { return ast_type_traits::DynTypedNode::create(Node); } template <> ast_type_traits::DynTypedNode createDynTypedNode(const NestedNameSpecifierLoc &Node) { return ast_type_traits::DynTypedNode::create(Node); } /// @} /// A \c RecursiveASTVisitor that builds a map from nodes to their /// parents as defined by the \c RecursiveASTVisitor. /// /// Note that the relationship described here is purely in terms of AST /// traversal - there are other relationships (for example declaration context) /// in the AST that are better modeled by special matchers. /// /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes. class ASTContext::ParentMap::ASTVisitor : public RecursiveASTVisitor<ASTVisitor> { public: ASTVisitor(ParentMap &Map, ASTContext &Context) : Map(Map), Context(Context) {} private: friend class RecursiveASTVisitor<ASTVisitor>; using VisitorBase = RecursiveASTVisitor<ASTVisitor>; bool shouldVisitTemplateInstantiations() const { return true; } bool shouldVisitImplicitCode() const { return true; } template <typename T, typename MapNodeTy, typename BaseTraverseFn, typename MapTy> bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse, MapTy *Parents) { if (!Node) return true; if (ParentStack.size() > 0) { // FIXME: Currently we add the same parent multiple times, but only // when no memoization data is available for the type. // For example when we visit all subexpressions of template // instantiations; this is suboptimal, but benign: the only way to // visit those is with hasAncestor / hasParent, and those do not create // new matches. // The plan is to enable DynTypedNode to be storable in a map or hash // map. The main problem there is to implement hash functions / // comparison operators for all types that DynTypedNode supports that // do not have pointer identity. auto &NodeOrVector = (*Parents)[MapNode]; if (NodeOrVector.isNull()) { if (const auto *D = ParentStack.back().get<Decl>()) NodeOrVector = D; else if (const auto *S = ParentStack.back().get<Stmt>()) NodeOrVector = S; else NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back()); } else { if (!NodeOrVector.template is<ParentVector *>()) { auto *Vector = new ParentVector( 1, getSingleDynTypedNodeFromParentMap(NodeOrVector)); delete NodeOrVector .template dyn_cast<ast_type_traits::DynTypedNode *>(); NodeOrVector = Vector; } auto *Vector = NodeOrVector.template get<ParentVector *>(); // Skip duplicates for types that have memoization data. // We must check that the type has memoization data before calling // std::find() because DynTypedNode::operator== can't compare all // types. bool Found = ParentStack.back().getMemoizationData() && std::find(Vector->begin(), Vector->end(), ParentStack.back()) != Vector->end(); if (!Found) Vector->push_back(ParentStack.back()); } } ParentStack.push_back(createDynTypedNode(Node)); bool Result = BaseTraverse(); ParentStack.pop_back(); return Result; } bool TraverseDecl(Decl *DeclNode) { return TraverseNode( DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); }, &Map.PointerParents); } bool TraverseStmt(Stmt *StmtNode) { Stmt *FilteredNode = StmtNode; if (auto *ExprNode = dyn_cast_or_null<Expr>(FilteredNode)) FilteredNode = Context.traverseIgnored(ExprNode); return TraverseNode(FilteredNode, FilteredNode, [&] { return VisitorBase::TraverseStmt(FilteredNode); }, &Map.PointerParents); } bool TraverseTypeLoc(TypeLoc TypeLocNode) { return TraverseNode( TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode), [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); }, &Map.OtherParents); } bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) { return TraverseNode( NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode), [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); }, &Map.OtherParents); } ParentMap &Map; ASTContext &Context; llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack; }; ASTContext::ParentMap::ParentMap(ASTContext &Ctx) { ASTVisitor(*this, Ctx).TraverseAST(Ctx); } ASTContext::DynTypedNodeList ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) { std::unique_ptr<ParentMap> &P = Parents[Traversal]; if (!P) // We build the parent map for the traversal scope (usually whole TU), as // hasAncestor can escape any subtree. P = std::make_unique<ParentMap>(*this); return P->getParents(Node); } bool ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImpl) { // No point trying to match an unavailable/deprecated mothod. if (MethodDecl->hasAttr<UnavailableAttr>() || MethodDecl->hasAttr<DeprecatedAttr>()) return false; if (MethodDecl->getObjCDeclQualifier() != MethodImpl->getObjCDeclQualifier()) return false; if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) return false; if (MethodDecl->param_size() != MethodImpl->param_size()) return false; for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), EF = MethodDecl->param_end(); IM != EM && IF != EF; ++IM, ++IF) { const ParmVarDecl *DeclVar = (*IF); const ParmVarDecl *ImplVar = (*IM); if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) return false; if (!hasSameType(DeclVar->getType(), ImplVar->getType())) return false; } return (MethodDecl->isVariadic() == MethodImpl->isVariadic()); } uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const { LangAS AS; if (QT->getUnqualifiedDesugaredType()->isNullPtrType()) AS = LangAS::Default; else AS = QT->getPointeeType().getAddressSpace(); return getTargetInfo().getNullPointerValue(AS); } unsigned ASTContext::getTargetAddressSpace(LangAS AS) const { if (isTargetAddressSpace(AS)) return toTargetAddressSpace(AS); else return (*AddrSpaceMap)[(unsigned)AS]; } QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { assert(Ty->isFixedPointType()); if (Ty->isSaturatedFixedPointType()) return Ty; switch (Ty->castAs<BuiltinType>()->getKind()) { default: llvm_unreachable("Not a fixed point type!"); case BuiltinType::ShortAccum: return SatShortAccumTy; case BuiltinType::Accum: return SatAccumTy; case BuiltinType::LongAccum: return SatLongAccumTy; case BuiltinType::UShortAccum: return SatUnsignedShortAccumTy; case BuiltinType::UAccum: return SatUnsignedAccumTy; case BuiltinType::ULongAccum: return SatUnsignedLongAccumTy; case BuiltinType::ShortFract: return SatShortFractTy; case BuiltinType::Fract: return SatFractTy; case BuiltinType::LongFract: return SatLongFractTy; case BuiltinType::UShortFract: return SatUnsignedShortFractTy; case BuiltinType::UFract: return SatUnsignedFractTy; case BuiltinType::ULongFract: return SatUnsignedLongFractTy; } } LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const { if (LangOpts.OpenCL) return getTargetInfo().getOpenCLBuiltinAddressSpace(AS); if (LangOpts.CUDA) return getTargetInfo().getCUDABuiltinAddressSpace(AS); return getLangASFromTargetAS(AS); } // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that // doesn't include ASTContext.h template clang::LazyGenerationalUpdatePtr< const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType clang::LazyGenerationalUpdatePtr< const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( const clang::ASTContext &Ctx, Decl *Value); unsigned char ASTContext::getFixedPointScale(QualType Ty) const { assert(Ty->isFixedPointType()); const TargetInfo &Target = getTargetInfo(); switch (Ty->castAs<BuiltinType>()->getKind()) { default: llvm_unreachable("Not a fixed point type!"); case BuiltinType::ShortAccum: case BuiltinType::SatShortAccum: return Target.getShortAccumScale(); case BuiltinType::Accum: case BuiltinType::SatAccum: return Target.getAccumScale(); case BuiltinType::LongAccum: case BuiltinType::SatLongAccum: return Target.getLongAccumScale(); case BuiltinType::UShortAccum: case BuiltinType::SatUShortAccum: return Target.getUnsignedShortAccumScale(); case BuiltinType::UAccum: case BuiltinType::SatUAccum: return Target.getUnsignedAccumScale(); case BuiltinType::ULongAccum: case BuiltinType::SatULongAccum: return Target.getUnsignedLongAccumScale(); case BuiltinType::ShortFract: case BuiltinType::SatShortFract: return Target.getShortFractScale(); case BuiltinType::Fract: case BuiltinType::SatFract: return Target.getFractScale(); case BuiltinType::LongFract: case BuiltinType::SatLongFract: return Target.getLongFractScale(); case BuiltinType::UShortFract: case BuiltinType::SatUShortFract: return Target.getUnsignedShortFractScale(); case BuiltinType::UFract: case BuiltinType::SatUFract: return Target.getUnsignedFractScale(); case BuiltinType::ULongFract: case BuiltinType::SatULongFract: return Target.getUnsignedLongFractScale(); } } unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { assert(Ty->isFixedPointType()); const TargetInfo &Target = getTargetInfo(); switch (Ty->castAs<BuiltinType>()->getKind()) { default: llvm_unreachable("Not a fixed point type!"); case BuiltinType::ShortAccum: case BuiltinType::SatShortAccum: return Target.getShortAccumIBits(); case BuiltinType::Accum: case BuiltinType::SatAccum: return Target.getAccumIBits(); case BuiltinType::LongAccum: case BuiltinType::SatLongAccum: return Target.getLongAccumIBits(); case BuiltinType::UShortAccum: case BuiltinType::SatUShortAccum: return Target.getUnsignedShortAccumIBits(); case BuiltinType::UAccum: case BuiltinType::SatUAccum: return Target.getUnsignedAccumIBits(); case BuiltinType::ULongAccum: case BuiltinType::SatULongAccum: return Target.getUnsignedLongAccumIBits(); case BuiltinType::ShortFract: case BuiltinType::SatShortFract: case BuiltinType::Fract: case BuiltinType::SatFract: case BuiltinType::LongFract: case BuiltinType::SatLongFract: case BuiltinType::UShortFract: case BuiltinType::SatUShortFract: case BuiltinType::UFract: case BuiltinType::SatUFract: case BuiltinType::ULongFract: case BuiltinType::SatULongFract: return 0; } } FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const { assert((Ty->isFixedPointType() || Ty->isIntegerType()) && "Can only get the fixed point semantics for a " "fixed point or integer type."); if (Ty->isIntegerType()) return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty), Ty->isSignedIntegerType()); bool isSigned = Ty->isSignedFixedPointType(); return FixedPointSemantics( static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned, Ty->isSaturatedFixedPointType(), !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding()); } APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const { assert(Ty->isFixedPointType()); return APFixedPoint::getMax(getFixedPointSemantics(Ty)); } APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const { assert(Ty->isFixedPointType()); return APFixedPoint::getMin(getFixedPointSemantics(Ty)); } QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const { assert(Ty->isUnsignedFixedPointType() && "Expected unsigned fixed point type"); switch (Ty->castAs<BuiltinType>()->getKind()) { case BuiltinType::UShortAccum: return ShortAccumTy; case BuiltinType::UAccum: return AccumTy; case BuiltinType::ULongAccum: return LongAccumTy; case BuiltinType::SatUShortAccum: return SatShortAccumTy; case BuiltinType::SatUAccum: return SatAccumTy; case BuiltinType::SatULongAccum: return SatLongAccumTy; case BuiltinType::UShortFract: return ShortFractTy; case BuiltinType::UFract: return FractTy; case BuiltinType::ULongFract: return LongFractTy; case BuiltinType::SatUShortFract: return SatShortFractTy; case BuiltinType::SatUFract: return SatFractTy; case BuiltinType::SatULongFract: return SatLongFractTy; default: llvm_unreachable("Unexpected unsigned fixed point type"); } } ParsedTargetAttr ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const { assert(TD != nullptr); ParsedTargetAttr ParsedAttr = TD->parse(); ParsedAttr.Features.erase( llvm::remove_if(ParsedAttr.Features, [&](const std::string &Feat) { return !Target->isValidFeatureName( StringRef{Feat}.substr(1)); }), ParsedAttr.Features.end()); return ParsedAttr; } void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, const FunctionDecl *FD) const { if (FD) getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD)); else Target->initFeatureMap(FeatureMap, getDiagnostics(), Target->getTargetOpts().CPU, Target->getTargetOpts().Features); } // Fills in the supplied string map with the set of target features for the // passed in function. void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, GlobalDecl GD) const { StringRef TargetCPU = Target->getTargetOpts().CPU; const FunctionDecl *FD = GD.getDecl()->getAsFunction(); if (const auto *TD = FD->getAttr<TargetAttr>()) { ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); // Make a copy of the features as passed on the command line into the // beginning of the additional features from the function to override. ParsedAttr.Features.insert( ParsedAttr.Features.begin(), Target->getTargetOpts().FeaturesAsWritten.begin(), Target->getTargetOpts().FeaturesAsWritten.end()); if (ParsedAttr.Architecture != "" && Target->isValidCPUName(ParsedAttr.Architecture)) TargetCPU = ParsedAttr.Architecture; // Now populate the feature map, first with the TargetCPU which is either // the default or a new one from the target attribute string. Then we'll use // the passed in features (FeaturesAsWritten) along with the new ones from // the attribute. Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, ParsedAttr.Features); } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) { llvm::SmallVector<StringRef, 32> FeaturesTmp; Target->getCPUSpecificCPUDispatchFeatures( SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end()); Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features); } else { Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Target->getTargetOpts().Features); } }
epiqc/ScaffCC
clang/lib/AST/ASTContext.cpp
C++
bsd-2-clause
408,247
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2011. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */ /*----------------------------------------------------------------------------*/ #include "Commands/WaitUntilCommand.h" #include "Timer.h" /** * A {@link WaitCommand} will wait until a certain match time before finishing. * This will wait until the game clock reaches some value, then continue to the * next command. * @see CommandGroup */ WaitUntilCommand::WaitUntilCommand(double time) : Command("WaitUntilCommand", time) { m_time = time; } WaitUntilCommand::WaitUntilCommand(const std::string &name, double time) : Command(name, time) { m_time = time; } void WaitUntilCommand::Initialize() {} void WaitUntilCommand::Execute() {} /** * Check if we've reached the actual finish time. */ bool WaitUntilCommand::IsFinished() { return Timer::GetMatchTime() >= m_time; } void WaitUntilCommand::End() {} void WaitUntilCommand::Interrupted() {}
FRC1296/CheezyDriver2016
third_party/allwpilib_2016/wpilibc/shared/src/Commands/WaitUntilCommand.cpp
C++
bsd-2-clause
1,164
using System; using TTengine.Core; using TTengine.Util; using Microsoft.Xna.Framework; using Game1; using Game1.Behaviors; namespace Game1.Actors { /** * companion of the hero that helps him */ public class Companion: ThingComp { public ChaseBehavior ChasingRedGuard, ChasingHero; //public CombatBehavior Combat; public RandomWanderBehavior Wandering; //public AttackBehavior Attacking; public static Companion Create() { return new Companion(); } public Companion() : base("pixie") { IsCollisionFree = false; SetColors(4f, new Color(38, 30, 240), new Color(150, 150, 255)); Pushing.Force = RandomMath.RandomBetween(1f, 1.5f); SubsumptionBehavior sub = new SubsumptionBehavior(); Add(sub); Combat = new CombatBehavior(typeof(RedGuard)); sub.Add(Combat); ChasingHero = new ChaseBehavior(Level.Current.pixie); ChasingHero.ChaseRange = 370f; ChasingHero.SatisfiedRange = 6f; ChasingHero.MoveDeltaTime = RandomMath.RandomBetween(1.2f, 1.5f); sub.Add(ChasingHero); ChasingRedGuard = new ChaseBehavior(typeof(RedGuard)); ChasingRedGuard.ChaseRange = 20f; ChasingRedGuard.MoveDeltaTime = RandomMath.RandomBetween(1.1f, 1.5f); sub.Add(ChasingRedGuard); Attacking = new AttackBehavior(Level.Current.pixie); Attacking.AttackDuration = RandomMath.RandomBetween(1.5f, 2.8f); sub.Add(Attacking); Wandering = new RandomWanderBehavior(2.7f, 11.3f); Wandering.MoveDeltaTime = RandomMath.RandomBetween(0.09f, 0.25f); sub.Add(Wandering); } protected override void OnUpdate(ref UpdateParams p) { base.OnUpdate(ref p); } } }
IndiegameGarden/Quest
Game1/Game1/Actors/Companion.cs
C#
bsd-2-clause
1,989
/* * RudePhysics.cpp * golf * * Created by Robert Rose on 9/8/08. * Copyright 2008 Bork 3D LLC. All rights reserved. * */ #include "Rude.h" #include "RudePhysics.h" #include "RudePhysicsObject.h" #include "RudeDebug.h" inline btScalar calculateCombinedFriction(float friction0,float friction1) { btScalar friction = friction0 * friction1; /*const btScalar MAX_FRICTION = 10.f; if (friction < -MAX_FRICTION) friction = -MAX_FRICTION; if (friction > MAX_FRICTION) friction = MAX_FRICTION;*/ return friction; } inline btScalar calculateCombinedRestitution(float restitution0,float restitution1) { return restitution0 * restitution1; } static bool CustomMaterialCombinerCallback(btManifoldPoint& cp, const btCollisionObject* colObj0,int partId0,int index0,const btCollisionObject* colObj1,int partId1,int index1) { btVector3 normal = cp.m_normalWorldOnB; //printf("normal: %f %f %f\n", normal.x(), normal.y(), normal.z()); float friction0 = colObj0->getFriction(); float friction1 = colObj1->getFriction(); float restitution0 = colObj0->getRestitution(); float restitution1 = colObj1->getRestitution(); RudePhysicsObject *obj0 = RudePhysics::GetInstance()->GetObject(colObj0); RudePhysicsObject *obj1 = RudePhysics::GetInstance()->GetObject(colObj1); if (colObj0->getCollisionFlags() & btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK) { RUDE_ASSERT(obj0, "Custom callback but no object registered"); RUDE_ASSERT(obj0->GetNotifyOnContact(), "No custom callback registered for object"); obj0->Contact(normal, obj1, partId0, partId1, &friction0, &restitution0); } if (colObj1->getCollisionFlags() & btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK) { RUDE_ASSERT(obj1, "Custom callback but no object registered"); RUDE_ASSERT(obj1->GetNotifyOnContact(), "No custom callback registered for object"); obj1->Contact(normal, obj0, partId1, partId0, &friction1, &restitution1); } cp.m_combinedFriction = calculateCombinedFriction(friction0,friction1); cp.m_combinedRestitution = calculateCombinedRestitution(restitution0,restitution1); //printf("Friction of impact: %f\n", cp.m_combinedFriction); //printf("Restitution of impact: %f\n", cp.m_combinedRestitution); //this return value is currently ignored, but to be on the safe side: return false if you don't calculate friction return true; } RudePhysics::RudePhysics() : m_dynamicsWorld(0) , m_precise(true) { } RudePhysics::~RudePhysics() { } RudePhysics * RudePhysics::GetInstance() { static RudePhysics * s_singleton = 0; if(s_singleton == 0) s_singleton = new RudePhysics(); return s_singleton; } void RudePhysics::Init() { if(m_dynamicsWorld) return; gContactAddedCallback = CustomMaterialCombinerCallback; int maxProxies = 1024; btVector3 worldAabbMin(-10000,-10000,-10000); btVector3 worldAabbMax(10000,10000,10000); m_broadphase = new btAxisSweep3(worldAabbMin,worldAabbMax,maxProxies); m_collisionConfiguration = new btDefaultCollisionConfiguration(); m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration); m_solver = new btSequentialImpulseConstraintSolver; m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration); m_dynamicsWorld->setGravity(btVector3(0,-32.2,0)); } void RudePhysics::Destroy() { if(m_dynamicsWorld) { delete m_dynamicsWorld; m_dynamicsWorld = 0; } if(m_solver) { delete m_solver; m_solver = 0; } if(m_dispatcher) { delete m_dispatcher; m_dispatcher = 0; } if(m_collisionConfiguration) { delete m_collisionConfiguration; m_collisionConfiguration = 0; } if(m_broadphase) { delete m_broadphase; m_broadphase = 0; } } void RudePhysics::AddObject(RudePhysicsObject *obj) { btRigidBody *btrb = obj->GetRigidBody(); RUDE_ASSERT(btrb, "Object has no rigid body"); m_dynamicsWorld->addRigidBody(btrb); m_objMap[btrb] = obj; } void RudePhysics::NextFrame(float delta) { if(m_dynamicsWorld) if(m_precise) m_dynamicsWorld->stepSimulation(delta,20, 1.0f/60.0f); else m_dynamicsWorld->stepSimulation(delta,20, 1.0f/30.0f); }
moof2k/golf
code/preview/Classes/RudePhysics.cpp
C++
bsd-2-clause
4,146
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ namespace MNHcC\Zend3bcHelper\Testing { // use the namespace of modules use MNHcC\Zend3bcHelper; return [ 'modules' => [ Zend3bcHelper::class, ], // These are various options for the listeners attached to the ModuleManager 'module_listener_options' => [ // This should be an array of paths in which modules reside. // If a string key is provided, the listener will consider that a module // namespace, the value of that key the specific path to that module's // Module class. 'module_paths' => [ '../../vendor', ], ], ]; }
MNHcC/Zend3bcHelper
test/config/application.config.php
PHP
bsd-2-clause
866
package com.jme3.glhelper; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import com.jme3.math.ColorRGBA; import com.jme3.shader.Shader; /** * OpenGL helper that does not rely on a specific binding. Its main purpose is to allow * to move the binding-agnostic OpenGL logic from the source code of the both renderers * to a single abstract renderer in order to ease the maintenance * * @author Julien Gouesse * */ public interface Helper { public static final int TEXTURE0 = 33984; //TODO: add Array, Format, TargetBuffer, TextureType, ShaderType, ShadeModel, BlendMode, CullFace, FillMode, DepthFunc, AlphaFunc public enum MatrixMode{ MODELVIEW(0x1700),PROJECTION(0x1701); private final int glConstant; private MatrixMode(int glConstant){ this.glConstant = glConstant; } public final int getGLConstant(){ return glConstant; } }; public enum BufferBit{ COLOR_BUFFER(16384),DEPTH_BUFFER(256),STENCIL_BUFFER(1024),ACCUM_BUFFER(512); private final int glConstant; private BufferBit(int glConstant){ this.glConstant = glConstant; } public final int getGLConstant(){ return glConstant; } } public enum Filter{ NEAREST(9728),LINEAR(9729); private final int glConstant; private Filter(int glConstant){ this.glConstant = glConstant; } public final int getGLConstant(){ return glConstant; } } public void useProgram(int program); public void setMatrixMode(MatrixMode matrixMode); public void loadMatrixf(FloatBuffer m); public void multMatrixf(FloatBuffer m); public void setViewPort(int x, int y, int width, int height); public void setBackgroundColor(ColorRGBA color); public void clear(BufferBit bufferBit); public void setDepthRange(float start, float end); public void setScissor(int x, int y, int width, int height); public int getUniformLocation(Shader shader,String name,ByteBuffer nameBuffer); }
chototsu/MikuMikuStudio
engine/src/jogl2/com/jme3/glhelper/Helper.java
Java
bsd-2-clause
1,955
/* * Copyright (c) 2016, JInterval Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 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. * * 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 HOLDER 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. */ package net.java.jinterval.expression.example; import net.java.jinterval.expression.CodeList; import net.java.jinterval.expression.Expression; import net.java.jinterval.expression.OptimizationProblem; /** * Формулы из Количественная оценка неопределённости пожарного риска. Сценарий * аварии "Пожар пролива ЛВЖ" Проблемы анализа риска, том 11, 2014Б ном. 4 */ public class FireRisk { /** * Enum to choose input variable */ public enum From { tpac_T_uw_d, L_d_theta, a_b_theta }; /** * Enum to choose objective function. */ public enum To { F, Fv, Fh, Fsqr } /** * Create optimization problem minimizing Fv on (l,d,theta) inputs. * * @return OptimizationProblem */ public static OptimizationProblem createOptimizationProblemLdMinFv() { return createOptimizationProblem(From.L_d_theta, To.Fv, false); } /** * Create optimization problem maximizing Fv on (tpac,T,uw,d) inputs. * * @return OptimizationProblem */ public static OptimizationProblem createOptimizationProblemTempMaxFv() { return createOptimizationProblem(From.tpac_T_uw_d, To.Fv, true); } /** * Create optimization problem * * @param from choose input variables * @param to choose objective function * @param neg true to negate objective function * @return OptimizationProblem */ public static OptimizationProblem createOptimizationProblem(From from, To to, boolean neg) { String[] box; switch (from) { case tpac_T_uw_d: box = new String[]{ "[50.0,170.0]", // tpac "[254.0,299.0]", // T "[2.3,9.0]", // uw "[15.2,34.8]" // d }; break; case L_d_theta: box = new String[]{ "[19.1,55.2]", // L "[15.2,34.8]", // d "[0,1.18]" // theta }; break; case a_b_theta: box = new String[]{ "[382/348,1104/152]", // a = 2*L/d "[2000/348,2000/152]", // b = 2*X/d "[0,1.18]" // theta }; break; default: throw new AssertionError(); } return new OptimizationProblem(createObjective(from, to, neg), box); } /** * Create objective function * * @param from choose input variables * @param to choose objective function * @param neg true to negate objective function * @return objective function */ public static Expression createObjective(From from, To to, boolean neg) { Subclass fr = new Subclass(from); Expression objective; switch (to) { case F: objective = fr.F; break; case Fv: objective = fr.Fv(); break; case Fh: objective = fr.Fh(); break; case Fsqr: objective = fr.Fsqr(); break; default: throw new AssertionError(); } return neg ? objective.neg().name("neg_" + objective.name()) : objective; } final CodeList cl; final From from; FireRisk(From from) { this.from = from; switch (from) { case tpac_T_uw_d: cl = CodeList.create("tpac", "T", "uw", "d"); break; case L_d_theta: cl = CodeList.create("L", "d", "theta"); break; case a_b_theta: cl = CodeList.create("a", "b", "theta"); break; default: throw new AssertionError(); } } boolean from(From from) { return this.from.ordinal() <= from.ordinal(); } Expression n(String literal) { return cl.lit(literal); } public static class Subclass extends FireRisk { Subclass(From from) { super(from); } // Constants public Expression m_prime = n("0.06").name("m_prime"); public Expression g = n("9.81").name("g"); public Expression Tnom = n("288.15").name("Tnom"); public Expression ro_v_nom = n("1.225").name("ro_v_nom"); public Expression X = n("100").name("X"); public Expression V_mu = n("22.413").name("V_mu"); public Expression k_factor = n("1.216").div(n("0.67668")).name("k_factor"); public Expression c1Pi = cl.pi().recip().name("c1Pi"); public Expression tpac = from(From.tpac_T_uw_d) ? cl.getInp(0) : null; public Expression T = from(From.tpac_T_uw_d) ? cl.getInp(1) : null; public Expression uw = from(From.tpac_T_uw_d) ? cl.getInp(2) : null; public Expression d = from(From.tpac_T_uw_d) ? cl.getInp(3) : from(From.L_d_theta) ? cl.getInp(1) : null; /*0*/ public Expression k = from(From.tpac_T_uw_d) ? k_factor.mul(tpac.rootn(3)).name("k") : null; public Expression mu0 = from(From.tpac_T_uw_d) ? n("7").mul(k).sub(n("21.5")).name("mu0") : null; public Expression mu1 = from(From.tpac_T_uw_d) ? n("0.76").sub(n("0.04").mul(k)).name("mu1") : null; public Expression mu2 = from(From.tpac_T_uw_d) ? n("0.0003").mul(k).sub(n("0.00245")).name("mu2") : null; /*1*/ public Expression mu = from(From.tpac_T_uw_d) ? mu0.add(mu1.mul(tpac)).add(mu2.mul(tpac.sqr())).name("mu") : null; /*2*/ public Expression ro_p = from(From.tpac_T_uw_d) ? mu.div(V_mu.mul(n("1").add(n("0.00367").mul(tpac)))).name("ro_p") : null; public Expression u_star_arg = from(From.tpac_T_uw_d) ? ro_p.div(m_prime.mul(g).mul(d)) : null; /*3*/ public Expression u_star = from(From.tpac_T_uw_d) ? uw.mul(u_star_arg.rootn(3)).max(n("1")).name("u_star") : null; /*4*/ public Expression ro_v = from(From.tpac_T_uw_d) ? Tnom.mul(ro_v_nom).div(T).name("ro_v") : null; /*5*/ public Expression L = from(From.tpac_T_uw_d) ? n("55") .mul(m_prime.pow(n("0.67"))) .div(g.pow(n("0.335"))) .mul(d.pow(n("0.665"))) .mul(u_star.pow(n("0.21"))) .div(ro_v.pow(n("0.67"))) .name("L") : from(From.L_d_theta) ? cl.getInp(0) : null; /*6*/ public Expression theta = from(From.tpac_T_uw_d) ? u_star.sqrt().recip().acos().name("theta") : from(From.L_d_theta) ? cl.getInp(2) : from(From.a_b_theta) ? cl.getInp(2) : null; /*7*/ public Expression a = from(From.L_d_theta) ? L.mul(n("2")).div(d).name("a") : from(From.a_b_theta) ? cl.getInp(0) : null; /*8*/ public Expression b = from(From.L_d_theta) ? n("2").mul(X).div(d).name("b") : from(From.a_b_theta) ? cl.getInp(1) : null; public Expression bp1 = b.add(n("1")).name("bp1"); public Expression bm1 = b.sub(n("1")).name("bm1"); public Expression sinth = theta.sin().name("sinth"); public Expression costh = theta.cos().name("costh"); public Expression A_arg = a.sqr() .add(bp1.sqr()) .sub(n("2").mul(a.mul(bp1).mul(sinth))) .name("A_arg"); /*9*/ public Expression A = A_arg.sqrt().name("A"); public Expression B_arg = a.sqr() .add(bm1.sqr()) .sub(n("2").mul(a.mul(bm1).mul(sinth))) .name("B_arg"); /*10*/ public Expression B = B_arg.sqrt().name("B"); public Expression C_arg = n("1").add((b.sqr().sub(n("1"))).mul(costh.sqr())).name("C_arg"); /*11*/ public Expression C = C_arg.sqrt().name("C"); public Expression D_arg = from(From.L_d_theta) ? n("2").mul(X).sub(d) .div(n("2").mul(X).add(d)) .name("D_arg") : from(From.a_b_theta) ? bm1.div(bp1).sqrt() : null; /*12*/ public Expression D = D_arg.sqrt().name("D"); /*13*/ public Expression E = from(From.L_d_theta) ? L.mul(costh) .div(X.sub(L.mul(sinth))) .name("E") : from(From.a_b_theta) ? a.mul(costh).div(b.sub(a.mul(sinth))) : null; /*14*/ public Expression F_arg = b.sqr().sub(n("1")).name("F_arg"); public Expression F = F_arg.sqrt().name("F"); public Expression ab = a.mul(b).name("ab"); public Expression AB = A.mul(B).name("AB"); public Expression S1arg = ab.sub(F.sqr().mul(sinth)) .div(F.mul(C)).name("S1arg"); public Expression S1 = S1arg.atan().name("S1"); public Expression S2arg = F.mul(sinth).div(C).name("S2arg"); public Expression S2 = S2arg.atan().name("S2"); public Expression S = S1.add(S2).name("S"); public Expression ADB = A.mul(D).div(B).name("ADB"); public Expression atanADB = ADB.atan().name("atanADB"); public Expression Fv() { Expression abFv = a.sqr() .add(b.add(n("1")).sqr()) .sub(n("2").mul(b).mul(n("1").add(a.mul(sinth)))) .name("abFv"); Expression Fv1 = E.neg().mul(D.atan()).name("Fv1"); Expression Fv2 = E.mul(abFv).div(AB).mul(atanADB).name("Fv2"); Expression Fv3 = costh.div(C).mul(S).name("Fv3"); Expression Fv = cl.pi().recip().mul(Fv1.add(Fv2.add(Fv3))).name("Fv"); return Fv; } public Expression Fh() { Expression abFh = a.sqr() .add(b.add(n("1")).sqr()) .sub(n("2").mul(b.add(n("1")).add(ab.mul(sinth)))) .name("abFh"); Expression Fh1 = D.recip().atan().name("Fh1"); Expression Fh2 = sinth.div(C).mul(S).name("Fh2"); Expression Fh3 = abFh.div(AB).mul(atanADB).name("Fh3"); Expression Fh = c1Pi.mul(Fh1.add(Fh2).sub(Fh3)).name("Fh"); return Fh; } public Expression Fsqr() { return Fv().sqr() .add(Fh().sqr()) .name("Fsqr"); } } }
jinterval/jinterval
jinterval-expression/src/main/java/net/java/jinterval/expression/example/FireRisk.java
Java
bsd-2-clause
12,563
// This file was procedurally generated from the following sources: // - src/dstr-binding/ary-ptrn-elem-obj-val-undef.case // - src/dstr-binding/error/cls-expr-meth.template /*--- description: Nested object destructuring with a value of `undefined` (class expression method) esid: sec-class-definitions-runtime-semantics-evaluation es6id: 14.5.16 features: [destructuring-binding] flags: [generated] info: | ClassExpression : class BindingIdentifieropt ClassTail 1. If BindingIdentifieropt is not present, let className be undefined. 2. Else, let className be StringValue of BindingIdentifier. 3. Let value be the result of ClassDefinitionEvaluation of ClassTail with argument className. [...] 14.5.14 Runtime Semantics: ClassDefinitionEvaluation 21. For each ClassElement m in order from methods a. If IsStatic of m is false, then i. Let status be the result of performing PropertyDefinitionEvaluation for m with arguments proto and false. [...] 14.3.8 Runtime Semantics: DefineMethod MethodDefinition : PropertyName ( StrictFormalParameters ) { FunctionBody } [...] 6. Let closure be FunctionCreate(kind, StrictFormalParameters, FunctionBody, scope, strict). If functionPrototype was passed as a parameter then pass its value as the functionPrototype optional argument of FunctionCreate. [...] 9.2.1 [[Call]] ( thisArgument, argumentsList) [...] 7. Let result be OrdinaryCallEvaluateBody(F, argumentsList). [...] 9.2.1.3 OrdinaryCallEvaluateBody ( F, argumentsList ) 1. Let status be FunctionDeclarationInstantiation(F, argumentsList). [...] 9.2.12 FunctionDeclarationInstantiation(func, argumentsList) [...] 23. Let iteratorRecord be Record {[[iterator]]: CreateListIterator(argumentsList), [[done]]: false}. 24. If hasDuplicates is true, then [...] 25. Else, b. Let formalStatus be IteratorBindingInitialization for formals with iteratorRecord and env as arguments. [...] 13.3.3.6 Runtime Semantics: IteratorBindingInitialization BindingElement : BindingPattern Initializeropt 1. If iteratorRecord.[[done]] is false, then [...] e. Else i. Let v be IteratorValue(next). [...] 4. Return the result of performing BindingInitialization of BindingPattern with v and environment as the arguments. 13.3.3.5 Runtime Semantics: BindingInitialization BindingPattern : ObjectBindingPattern 1. Let valid be RequireObjectCoercible(value). 2. ReturnIfAbrupt(valid). ---*/ var C = class { method([{ x }]) {} }; var c = new C(); assert.throws(TypeError, function() { c.method([]); });
sebastienros/jint
Jint.Tests.Test262/test/language/expressions/class/dstr-meth-ary-ptrn-elem-obj-val-undef.js
JavaScript
bsd-2-clause
2,782
package cfvbaibai.cardfantasy.engine.feature; import java.util.List; import cfvbaibai.cardfantasy.CardFantasyRuntimeException; import cfvbaibai.cardfantasy.data.Feature; import cfvbaibai.cardfantasy.engine.CardInfo; import cfvbaibai.cardfantasy.engine.EntityInfo; import cfvbaibai.cardfantasy.engine.FeatureInfo; import cfvbaibai.cardfantasy.engine.FeatureResolver; import cfvbaibai.cardfantasy.engine.HeroDieSignal; import cfvbaibai.cardfantasy.engine.Player; public final class WeakenAllFeature { public static void apply(FeatureResolver resolver, FeatureInfo featureInfo, EntityInfo attacker, Player defenderPlayer) throws HeroDieSignal { if (defenderPlayer == null) { throw new CardFantasyRuntimeException("defenderPlayer is null"); } if (attacker == null) { return; } Feature feature = featureInfo.getFeature(); List<CardInfo> defenders = defenderPlayer.getField().getAliveCards(); resolver.getStage().getUI().useSkill(attacker, defenders, feature, true); WeakenFeature.weakenCard(resolver, featureInfo, featureInfo.getFeature().getImpact(), attacker, defenders); } }
catree1988/CardFantasy-master
workspace/CardFantasyCore/src/cfvbaibai/cardfantasy/engine/feature/WeakenAllFeature.java
Java
bsd-2-clause
1,173
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-06-06 02:47 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Car', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('car_model', models.CharField(max_length=20)), ('color', models.CharField(max_length=20)), ('year', models.SmallIntegerField(help_text='Use year as YYYY.', validators=[django.core.validators.RegexValidator('^[0-9]{4}$', 'Year in invalid format!', 'invalid')])), ('mileage', models.IntegerField(default=0, help_text='Or your car is brand new or it have some mileage traveled', validators=[django.core.validators.MinValueValidator(0)])), ], ), migrations.CreateModel( name='OilChange', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateTimeField(verbose_name='date changed')), ('mileage', models.IntegerField(default=0, validators=[django.core.validators.MinValueValidator(0)])), ('car', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='car.Car')), ], ), migrations.CreateModel( name='Refuel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateTimeField(verbose_name='date refueled')), ('liters', models.DecimalField(decimal_places=3, max_digits=7)), ('fuel_price', models.DecimalField(decimal_places=2, max_digits=4)), ('mileage', models.IntegerField(default=0, validators=[django.core.validators.MinValueValidator(0)])), ('fuel_type', models.CharField(choices=[('Regular gas', 'Regular gas'), ('Premium gas', 'Premium gas'), ('Alcohol', 'Alcohol'), ('Diesel', 'Diesel')], default='Regular gas', max_length=20)), ('car', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='car.Car')), ], ), ]
italopaiva/your.car
yourcar/car/migrations/0001_initial.py
Python
bsd-2-clause
2,468
"""Widget for creating classes from non-numeric attribute by substrings""" import re from itertools import count import numpy as np from AnyQt.QtWidgets import QGridLayout, QLabel, QLineEdit, QSizePolicy from AnyQt.QtCore import QSize, Qt from Orange.data import StringVariable, DiscreteVariable, Domain from Orange.data.table import Table from Orange.statistics.util import bincount from Orange.preprocess.transformation import Transformation, Lookup from Orange.widgets import gui, widget from Orange.widgets.settings import DomainContextHandler, ContextSetting from Orange.widgets.utils.itemmodels import DomainModel from Orange.widgets.widget import Msg def map_by_substring(a, patterns, case_sensitive, match_beginning): """ Map values in a using a list of patterns. The patterns are considered in order of appearance. Args: a (np.array): input array of `dtype` `str` patterns (list of str): list of stirngs case_sensitive (bool): case sensitive match match_beginning (bool): match only at the beginning of the string Returns: np.array of floats representing indices of matched patterns """ res = np.full(len(a), np.nan) if not case_sensitive: a = np.char.lower(a) patterns = (pattern.lower() for pattern in patterns) for val_idx, pattern in reversed(list(enumerate(patterns))): indices = np.char.find(a, pattern) matches = indices == 0 if match_beginning else indices != -1 res[matches] = val_idx return res class ValueFromStringSubstring(Transformation): """ Transformation that computes a discrete variable from a string variable by pattern matching. Given patterns `["abc", "a", "bc", ""]`, string data `["abcd", "aa", "bcd", "rabc", "x"]` is transformed to values of the new attribute with indices`[0, 1, 2, 0, 3]`. Args: variable (:obj:`~Orange.data.StringVariable`): the original variable patterns (list of str): list of string patterns case_sensitive (bool, optional): if set to `True`, the match is case sensitive match_beginning (bool, optional): if set to `True`, the pattern must appear at the beginning of the string """ def __init__(self, variable, patterns, case_sensitive=False, match_beginning=False): super().__init__(variable) self.patterns = patterns self.case_sensitive = case_sensitive self.match_beginning = match_beginning def transform(self, c): """ Transform the given data. Args: c (np.array): an array of type that can be cast to dtype `str` Returns: np.array of floats representing indices of matched patterns """ nans = np.equal(c, None) c = c.astype(str) c[nans] = "" res = map_by_substring( c, self.patterns, self.case_sensitive, self.match_beginning) res[nans] = np.nan return res class ValueFromDiscreteSubstring(Lookup): """ Transformation that computes a discrete variable from discrete variable by pattern matching. Say that the original attribute has values `["abcd", "aa", "bcd", "rabc", "x"]`. Given patterns `["abc", "a", "bc", ""]`, the values are mapped to the values of the new attribute with indices`[0, 1, 2, 0, 3]`. Args: variable (:obj:`~Orange.data.DiscreteVariable`): the original variable patterns (list of str): list of string patterns case_sensitive (bool, optional): if set to `True`, the match is case sensitive match_beginning (bool, optional): if set to `True`, the pattern must appear at the beginning of the string """ def __init__(self, variable, patterns, case_sensitive=False, match_beginning=False): super().__init__(variable, []) self.case_sensitive = case_sensitive self.match_beginning = match_beginning self.patterns = patterns # Finally triggers computation of the lookup def __setattr__(self, key, value): """__setattr__ is overloaded to recompute the lookup table when the patterns, the original attribute or the flags change.""" super().__setattr__(key, value) if hasattr(self, "patterns") and \ key in ("case_sensitive", "match_beginning", "patterns", "variable"): self.lookup_table = map_by_substring( self.variable.values, self.patterns, self.case_sensitive, self.match_beginning) class OWCreateClass(widget.OWWidget): name = "Create Class" description = "Create class attribute from a string attribute" icon = "icons/CreateClass.svg" category = "Data" keywords = ["data"] inputs = [("Data", Table, "set_data")] outputs = [("Data", Table)] want_main_area = False settingsHandler = DomainContextHandler() attribute = ContextSetting(None) class_name = ContextSetting("class") rules = ContextSetting({}) match_beginning = ContextSetting(False) case_sensitive = ContextSetting(False) TRANSFORMERS = {StringVariable: ValueFromStringSubstring, DiscreteVariable: ValueFromDiscreteSubstring} class Warning(widget.OWWidget.Warning): no_nonnumeric_vars = Msg("Data contains only numeric variables.") def __init__(self): super().__init__() self.data = None # The following lists are of the same length as self.active_rules #: list of pairs with counts of matches for each patter when the # patterns are applied in order and when applied on the entire set, # disregarding the preceding patterns self.match_counts = [] #: list of list of QLineEdit: line edit pairs for each pattern self.line_edits = [] #: list of QPushButton: list of remove buttons self.remove_buttons = [] #: list of list of QLabel: pairs of labels with counts self.counts = [] combo = gui.comboBox( self.controlArea, self, "attribute", label="From column: ", box=True, orientation=Qt.Horizontal, callback=self.update_rules, model=DomainModel(valid_types=(StringVariable, DiscreteVariable))) # Don't use setSizePolicy keyword argument here: it applies to box, # not the combo combo.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) patternbox = gui.vBox(self.controlArea, box=True) #: QWidget: the box that contains the remove buttons, line edits and # count labels. The lines are added and removed dynamically. self.rules_box = rules_box = QGridLayout() patternbox.layout().addLayout(self.rules_box) box = gui.hBox(patternbox) gui.button( box, self, "+", callback=self.add_row, autoDefault=False, flat=True, minimumSize=(QSize(20, 20))) gui.rubber(box) self.rules_box.setColumnMinimumWidth(1, 70) self.rules_box.setColumnMinimumWidth(0, 10) self.rules_box.setColumnStretch(0, 1) self.rules_box.setColumnStretch(1, 1) self.rules_box.setColumnStretch(2, 100) rules_box.addWidget(QLabel("Name"), 0, 1) rules_box.addWidget(QLabel("Substring"), 0, 2) rules_box.addWidget(QLabel("#Instances"), 0, 3, 1, 2) self.update_rules() gui.lineEdit( self.controlArea, self, "class_name", label="Name for the new class:", box=True, orientation=Qt.Horizontal) optionsbox = gui.vBox(self.controlArea, box=True) gui.checkBox( optionsbox, self, "match_beginning", "Match only at the beginning", callback=self.options_changed) gui.checkBox( optionsbox, self, "case_sensitive", "Case sensitive", callback=self.options_changed) layout = QGridLayout() gui.widgetBox(self.controlArea, orientation=layout) for i in range(3): layout.setColumnStretch(i, 1) layout.addWidget(self.report_button, 0, 0) apply = gui.button(None, self, "Apply", autoDefault=False, callback=self.apply) layout.addWidget(apply, 0, 2) # TODO: Resizing upon changing the number of rules does not work self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) @property def active_rules(self): """ Returns the class names and patterns corresponding to the currently selected attribute. If the attribute is not yet in the dictionary, set the default. """ return self.rules.setdefault(self.attribute and self.attribute.name, [["", ""], ["", ""]]) def rules_to_edits(self): """Fill the line edites with the rules from the current settings.""" for editr, textr in zip(self.line_edits, self.active_rules): for edit, text in zip(editr, textr): edit.setText(text) def set_data(self, data): """Input data signal handler.""" self.closeContext() self.rules = {} self.data = data model = self.controls.attribute.model() model.set_domain(data and data.domain) self.Warning.no_nonnumeric_vars(shown=data is not None and not model) if not model: self.attribute = None self.send("Data", None) return self.attribute = model[0] self.openContext(data) self.update_rules() self.apply() def update_rules(self): """Called when the rules are changed: adjust the number of lines in the form and fill them, update the counts. The widget does not have auto-apply.""" self.adjust_n_rule_rows() self.rules_to_edits() self.update_counts() # TODO: Indicator that changes need to be applied def options_changed(self): self.update_counts() def adjust_n_rule_rows(self): """Add or remove lines if needed and fix the tab order.""" def _add_line(): self.line_edits.append([]) n_lines = len(self.line_edits) for coli in range(1, 3): edit = QLineEdit() self.line_edits[-1].append(edit) self.rules_box.addWidget(edit, n_lines, coli) edit.textChanged.connect(self.sync_edit) button = gui.button( None, self, label='×', flat=True, height=20, styleSheet='* {font-size: 16pt; color: silver}' '*:hover {color: black}', autoDefault=False, callback=self.remove_row) button.setMinimumSize(QSize(12, 20)) self.remove_buttons.append(button) self.rules_box.addWidget(button, n_lines, 0) self.counts.append([]) for coli, kwargs in enumerate( (dict(alignment=Qt.AlignRight), dict(alignment=Qt.AlignLeft, styleSheet="color: gray"))): label = QLabel(**kwargs) self.counts[-1].append(label) self.rules_box.addWidget(label, n_lines, 3 + coli) def _remove_line(): for edit in self.line_edits.pop(): edit.deleteLater() self.remove_buttons.pop().deleteLater() for label in self.counts.pop(): label.deleteLater() def _fix_tab_order(): prev = None for row, rule in zip(self.line_edits, self.active_rules): for col_idx, edit in enumerate(row): edit.row, edit.col_idx = rule, col_idx if prev is not None: self.setTabOrder(prev, edit) prev = edit n = len(self.active_rules) while n > len(self.line_edits): _add_line() while len(self.line_edits) > n: _remove_line() _fix_tab_order() def add_row(self): """Append a new row at the end.""" self.active_rules.append(["", ""]) self.adjust_n_rule_rows() self.update_counts() def remove_row(self): """Remove a row.""" remove_idx = self.remove_buttons.index(self.sender()) del self.active_rules[remove_idx] self.update_rules() self.update_counts() def sync_edit(self, text): """Handle changes in line edits: update the active rules and counts""" edit = self.sender() edit.row[edit.col_idx] = text self.update_counts() def class_labels(self): """Construct a list of class labels. Empty labels are replaced with C1, C2, C3. If C<n> already appears in the list of values given by the user, the labels start at C<n+1> instead. """ largest_c = max((int(label[1:]) for label, _ in self.active_rules if re.match("^C\\d+", label)), default=0) class_count = count(largest_c + 1) return [label_edit.text() or "C{}".format(next(class_count)) for label_edit, _ in self.line_edits] def update_counts(self): """Recompute and update the counts of matches.""" def _matcher(strings, pattern): """Return indices of strings into patterns; consider case sensitivity and matching at the beginning. The given strings are assumed to be in lower case if match is case insensitive. Patterns are fixed on the fly.""" if not self.case_sensitive: pattern = pattern.lower() indices = np.char.find(strings, pattern.strip()) return indices == 0 if self.match_beginning else indices != -1 def _lower_if_needed(strings): return strings if self.case_sensitive else np.char.lower(strings) def _string_counts(): """ Generate pairs of arrays for each rule until running out of data instances. np.sum over the two arrays in each pair gives the number of matches of the remaining instances (considering the order of patterns) and of the original data. For _string_counts, the arrays contain bool masks referring to the original data """ nonlocal data data = data.astype(str) data = data[~np.char.equal(data, "")] data = _lower_if_needed(data) remaining = np.array(data) for _, pattern in self.active_rules: matching = _matcher(remaining, pattern) total_matching = _matcher(data, pattern) yield matching, total_matching remaining = remaining[~matching] if len(remaining) == 0: break def _discrete_counts(): """ Generate pairs similar to _string_counts, except that the arrays contain bin counts for the attribute's values matching the pattern. """ attr_vals = np.array(attr.values) attr_vals = _lower_if_needed(attr_vals) bins = bincount(data, max_val=len(attr.values) - 1)[0] remaining = np.array(bins) for _, pattern in self.active_rules: matching = _matcher(attr_vals, pattern) yield remaining[matching], bins[matching] remaining[matching] = 0 if not np.any(remaining): break def _clear_labels(): """Clear all labels""" for lab_matched, lab_total in self.counts: lab_matched.setText("") lab_total.setText("") def _set_labels(): """Set the labels to show the counts""" for (n_matched, n_total), (lab_matched, lab_total), (lab, patt) in \ zip(self.match_counts, self.counts, self.active_rules): n_before = n_total - n_matched lab_matched.setText("{}".format(n_matched)) if n_before and (lab or patt): lab_total.setText("+ {}".format(n_before)) if n_matched: tip = "{} of the {} matching instances are already " \ "covered above".format(n_before, n_total) else: tip = "All matching instances are already covered above" lab_total.setToolTip(tip) lab_matched.setToolTip(tip) def _set_placeholders(): """Set placeholders for empty edit lines""" matches = [n for n, _ in self.match_counts] + \ [0] * len(self.line_edits) for n_matched, (_, patt) in zip(matches, self.line_edits): if not patt.text(): patt.setPlaceholderText( "(remaining instances)" if n_matched else "(unused)") labels = self.class_labels() for label, (lab_edit, _) in zip(labels, self.line_edits): if not lab_edit.text(): lab_edit.setPlaceholderText(label) _clear_labels() attr = self.attribute if attr is None: return counters = {StringVariable: _string_counts, DiscreteVariable: _discrete_counts} data = self.data.get_column_view(attr)[0] self.match_counts = [[int(np.sum(x)) for x in matches] for matches in counters[type(attr)]()] _set_labels() _set_placeholders() def apply(self): """Output the transformed data.""" if not self.attribute: self.send("Data", None) return domain = self.data.domain rules = self.active_rules # Transposition + stripping valid_rules = [label or pattern or n_matches for (label, pattern), n_matches in zip(rules, self.match_counts)] patterns = [pattern for (_, pattern), valid in zip(rules, valid_rules) if valid] names = [name for name, valid in zip(self.class_labels(), valid_rules) if valid] transformer = self.TRANSFORMERS[type(self.attribute)] compute_value = transformer( self.attribute, patterns, self.case_sensitive, self.match_beginning) new_class = DiscreteVariable( self.class_name, names, compute_value=compute_value) new_domain = Domain( domain.attributes, new_class, domain.metas + domain.class_vars) new_data = Table(new_domain, self.data) self.send("Data", new_data) def send_report(self): def _cond_part(): rule = "<b>{}</b> ".format(class_name) if patt: rule += "if <b>{}</b> contains <b>{}</b>".format( self.attribute.name, patt) else: rule += "otherwise" return rule def _count_part(): if not n_matched: return "all {} matching instances are already covered " \ "above".format(n_total) elif n_matched < n_total and patt: return "{} matching instances (+ {} that are already " \ "covered above".format(n_matched, n_total - n_matched) else: return "{} matching instances".format(n_matched) if not self.attribute: return self.report_items("Input", [("Source attribute", self.attribute.name)]) output = "" names = self.class_labels() for (n_matched, n_total), class_name, (lab, patt) in \ zip(self.match_counts, names, self.active_rules): if lab or patt or n_total: output += "<li>{}; {}</li>".format(_cond_part(), _count_part()) if output: self.report_items("Output", [("Class name", self.class_name)]) self.report_raw("<ol>{}</ol>".format(output)) def main(): # pragma: no cover """Simple test for manual inspection of the widget""" import sys from AnyQt.QtWidgets import QApplication a = QApplication(sys.argv) table = Table("zoo") ow = OWCreateClass() ow.show() ow.set_data(table) a.exec() ow.saveSettings() if __name__ == "__main__": # pragma: no cover main()
cheral/orange3
Orange/widgets/data/owcreateclass.py
Python
bsd-2-clause
20,686
<?php class Owlcarousel_Kwc_Carousel_Component extends Kwc_Abstract_List_Component { public static function getSettings() { $ret = parent::getSettings(); $ret['componentName'] = trlKwfStatic('List Carousel'); $ret['componentCategory'] = 'media'; $ret['generators']['child']['component'] = 'Owlcarousel_Kwc_Carousel_Image_Component'; $ret['carouselConfig'] = array( 'loop' => true, 'center' => true, 'items' => 2, 'nav' => true, 'dots' => false, 'margin' => 10, 'smartSpeed' => 1500, 'touchSmartSpeed' => 600, 'startRandom' => false, 'autoplay' => false, 'autoplayTimeout' => 7000, 'responsiveRefreshRate' => 90 ); $ret['assetsDefer']['dep'][] = 'owlcarousel'; return $ret; } public function getTemplateVars() { $ret = parent::getTemplateVars(); $ret['config'] = array( 'carouselConfig' => $this->_getSetting('carouselConfig'), 'countItems' => count($ret['listItems']), 'contentWidth' => $this->getContentWidth() ); return $ret; } }
koala-framework/kwf-owlcarousel
Owlcarousel/Kwc/Carousel/Component.php
PHP
bsd-2-clause
1,236
""" This is a subfile for IsyClass.py These funtions are accessable via the Isy class opj """ __author__ = 'Peter Shipley <peter.shipley@gmail.com>' __copyright__ = "Copyright (C) 2013 Peter Shipley" __license__ = "BSD" import time ## ## Climate funtions ## def load_clim(self): """ Load climate data from ISY device args: none internal function call """ if self.debug & 0x01: print("load_clim") clim_tree = self._getXMLetree("/rest/climate") self.climateinfo = dict() if clim_tree is None: return # Isy._printXML(self.climateinfo) for cl in clim_tree.iter("climate"): for k, v in cl.items(): self.climateinfo[k] = v for ce in list(cl): self.climateinfo[ce.tag] = ce.text self.climateinfo["time"] = time.gmtime() def clim_get_val(self, prop): pass def clim_query(self): """ returns dictionary of climate info """ if not self.climateinfo: self.load_clim() # # ADD CODE to check self.cachetime # return self.climateinfo def clim_iter(self): """ Iterate though climate values args: None returns: Return an iterator over the climate values """ if not self.climateinfo: self.load_clim() k = self.climateinfo.keys() for p in k: yield self.climateinfo[p] # Do nothing # (syntax check) # if __name__ == "__main__": import __main__ print(__main__.__file__) print("syntax ok") exit(0)
fxstein/ISYlib-python
ISY/_isyclimate.py
Python
bsd-2-clause
1,533
#!/usr/bin/env python3 from zested.main import main if __name__ == "__main__": main()
Luthaf/Zested
Zested.py
Python
bsd-2-clause
91
ActiveAdmin.register Lecture do menu parent: "Program" end
FIN-Vorkurs/finvorkurs
app/admin/lectures.rb
Ruby
bsd-2-clause
61
from __future__ import print_function import re from streamlink.plugin import Plugin from streamlink.plugin.api import http, useragents from streamlink.stream import HDSStream from streamlink.stream import HLSStream class TF1(Plugin): url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(\w+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) api_url = "http://www.wat.tv/get/{0}/591997" swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci"} hls_channel_remap = {"lci": "LCI", "tf1": "V4"} @classmethod def can_handle_url(cls, url): return cls.url_re.match(url) is not None def _get_hds_streams(self, channel): channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) manifest_url = http.get(self.api_url.format(channel), params={"getURL": 1}, headers={"User-Agent": useragents.FIREFOX}).text for s in HDSStream.parse_manifest(self.session, manifest_url, pvswf=self.swf_url, headers={"User-Agent": useragents.FIREFOX}).items(): yield s def _get_hls_streams(self, channel): channel = self.hls_channel_remap.get(channel, channel) embed_url = self.embed_url.format(channel) self.logger.debug("Found embed URL: {0}", embed_url) # page needs to have a mobile user agent embed_page = http.get(embed_url, headers={"User-Agent": useragents.ANDROID}) m = self.embed_re.search(embed_page.text) if m: hls_stream_url = m.group(1) try: for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): yield s except Exception: self.logger.error("Failed to load the HLS playlist for {0}", channel) def _get_streams(self): m = self.url_re.match(self.url) if m: channel = m.group(1) or m.group(2) self.logger.debug("Found channel {0}", channel) for s in self._get_hds_streams(channel): yield s for s in self._get_hls_streams(channel): yield s __plugin__ = TF1
mmetak/streamlink
src/streamlink/plugins/tf1.py
Python
bsd-2-clause
2,485
// // RemotePhotoTool - remote camera control software // Copyright (C) 2008-2014 Michael Fink // /// \file BulbReleaseControl.hpp Canon control - Release control for Bulb mode // #pragma once // includes /// \brief bulb shutter release control /// this object is created by RemoteReleaseControl::StartBulb; just destroy it to stop bulb mode class BulbReleaseControl { public: /// dtor virtual ~BulbReleaseControl() {} /// returns elapsed time, in seconds, since bulb start virtual double ElapsedTime() const = 0; /// stops bulb method; can be used when the shared_ptr of BulbReleaseControl /// cannot be destroyed, e.g. since it is held somewhere (e.g. Lua) virtual void Stop() = 0; };
vividos/RemotePhotoTool
src/CameraControl/exports/BulbReleaseControl.hpp
C++
bsd-2-clause
712
// Copyright 2011, Shelby Ramsey. All rights reserved. // Use of this code is governed by a BSD license that can be // found in the LICENSE.txt file. package sipparser // Imports from the go standard library import ( "testing" ) func TestCseq(t *testing.T) { sm := &SipMsg{} sm.parseCseq("100 INVITE") if sm.Error != nil { t.Errorf("[TestCseq] Error parsing cseq: \"100 INVITE\". Received err: " + sm.Error.Error()) } if sm.Cseq.Digit != "100" { t.Errorf("[TestCseq] Error parsing cseq: \"100 INVITE\". Digit should be 100.") } if sm.Cseq.Method != "INVITE" { t.Errorf("[TestCseq] Error parsing cseq: \"100 INVITE\". Method should be \"INVITE\".") } }
spaghetty/sip_parser
cseq_test.go
GO
bsd-2-clause
674
import bcrypt def hash_password(password): default_rounds = 14 bcrypt_salt = bcrypt.gensalt(default_rounds) hashed_password = bcrypt.hashpw(password, bcrypt_salt) return hashed_password def check_password(password, hashed): return bcrypt.checkpw(password, hashed)
fdemian/Morpheus
api/Crypto.py
Python
bsd-2-clause
288
require "tmpdir" require "pathname" HOMEBREW_TEMP = Pathname.new(ENV["HOMEBREW_TEMP"] || Dir.tmpdir) TEST_TMPDIR = ENV.fetch("HOMEBREW_TEST_TMPDIR") { |k| dir = Dir.mktmpdir("homebrew_tests", HOMEBREW_TEMP) at_exit { FileUtils.remove_entry(dir) } ENV[k] = dir } HOMEBREW_PREFIX = Pathname.new(TEST_TMPDIR).join("prefix") HOMEBREW_SEREPOSITORY = HOMEBREW_PREFIX HOMEBREW_LIBRARY = HOMEBREW_SEREPOSITORY+"Library" HOMEBREW_LIBRARY_PATH = Pathname.new(File.expand_path("../../..", __FILE__)) HOMEBREW_LOAD_PATH = [File.expand_path("..", __FILE__), HOMEBREW_LIBRARY_PATH].join(":") HOMEBREW_CACHE = HOMEBREW_PREFIX.parent+"cache" HOMEBREW_CACHE_FORMULA = HOMEBREW_PREFIX.parent+"formula_cache" HOMEBREW_CELLAR = HOMEBREW_PREFIX.parent+"cellar" HOMEBREW_LOGS = HOMEBREW_PREFIX.parent+"logs"
pampata/homebrew
Library/Homebrew/test/lib/config.rb
Ruby
bsd-2-clause
840
// Copyright (c) 2019 ASMlover. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // 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 HOLDER 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. #include <cstring> #include "vm.hh" #include "object.hh" namespace lvm { Object::Object(ObjType t) : type_(t) { auto* vm = get_running_vm(); if (vm != nullptr) vm->put_in(this); } StringObject* Object::as_string(void) const { return dynamic_cast<StringObject*>(const_cast<Object*>(this)); } const char* Object::as_cstring(void) const { return as_string()->c_str(); } StringObject* Object::create_string(const std::string& s) { return create_string(s.data(), static_cast<int>(s.size())); } StringObject* Object::create_string(const char* s, int n, bool placement) { StringObject* strobj; if (placement) { strobj = new StringObject(); strobj->init_from_string(s, n); } else { strobj = new StringObject(s, n); } return strobj; } StringObject* Object::concat_string(const Object* x, const Object* y) { auto* a = x->as_string(); auto* b = y->as_string(); int length = a->length() + b->length(); char* chars = new char[length + 1]; std::memcpy(chars, a->c_str(), a->length()); std::memcpy(chars + a->length(), b->c_str(), b->length()); chars[length] = 0; return create_string(chars, length); } StringObject::StringObject(void) : Object(ObjType::STRING) { } StringObject::~StringObject(void) { release_string(); } void StringObject::release_string(void) { if (chars_ != nullptr) { delete [] chars_; chars_ = nullptr; } length_ = 0; } StringObject::StringObject(const char* s) : Object(ObjType::STRING) , length_(static_cast<int>(std::strlen(s))) , chars_(new char[length_ + 1]) { std::memcpy(chars_, s, length_); chars_[length_] = 0; } StringObject::StringObject(const char* s, int n) : Object(ObjType::STRING) , length_(n) , chars_(new char[length_ + 1]) { std::memcpy(chars_, s, length_); chars_[length_] = 0; } StringObject::StringObject(const std::string& s) : Object(ObjType::STRING) , length_(static_cast<int>(s.size())) , chars_(new char[length_ + 1]) { std::memcpy(chars_, s.data(), length_); chars_[length_] = 0; } StringObject::StringObject(const StringObject& s) : Object(ObjType::STRING) , length_(s.length_) , chars_(new char[length_ + 1]) { std::memcpy(chars_, s.chars_, length_); chars_[length_] = 0; } StringObject::StringObject(StringObject&& s) : Object(ObjType::STRING) { std::swap(length_, s.length_); std::swap(chars_, s.chars_); } StringObject& StringObject::operator=(const std::string& s) { return reset(s), *this; } StringObject& StringObject::operator=(const StringObject& s) { if (this != &s) { if (chars_ != nullptr) delete [] chars_; length_ = s.length_; chars_ = new char[length_ + 1]; std::memcpy(chars_, s.chars_, length_); chars_[length_] = 0; } return *this; } StringObject& StringObject::operator=(StringObject&& s) { if (this != &s) { release_string(); std::swap(length_, s.length_); std::swap(chars_, s.chars_); } return *this; } void StringObject::reset(void) { release_string(); } void StringObject::reset(const char* s) { reset(s, static_cast<int>(std::strlen(s))); } void StringObject::reset(const char* s, int n) { release_string(); length_ = n; chars_ = new char[length_ + 1]; std::memcpy(chars_, s, length_); chars_[length_] = 0; } void StringObject::reset(const std::string& s) { reset(s.data(), static_cast<int>(s.size())); } void StringObject::reset(const StringObject& s) { if (this != &s) { if (chars_ != nullptr) delete [] chars_; length_ = s.length_; chars_ = new char[length_ + 1]; std::memcpy(chars_, s.chars_, length_); chars_[length_] = 0; } } void StringObject::reset(StringObject&& s) { if (this != &s) { release_string(); std::swap(length_, s.length_); std::swap(chars_, s.chars_); } } void StringObject::init_from_string(const char* s) { init_from_string(s, static_cast<int>(std::strlen(s))); } void StringObject::init_from_string(const char* s, int n) { if (chars_ != s || length_ != n) { if (chars_ != nullptr) delete [] chars_; length_ = n; chars_ = const_cast<char*>(s); } } void StringObject::init_from_string(const std::string& s) { init_from_string(s.data(), static_cast<int>(s.size())); } bool StringObject::is_equal(const Object* r) const { if (this == r) return true; auto* o = r->as_string(); return o != nullptr && length_ == o->length_ && std::memcmp(chars_, o->chars_, length_) == 0; } bool StringObject::is_truthy(void) const { return chars_ != nullptr && length_ != 0; } std::string StringObject::stringify(void) const { return chars_; } }
ASMlover/study
cplusplus/lvmpp-learn/lvmpp16/object.cc
C++
bsd-2-clause
5,997
package com.zjgsu.abroadStu.model; import java.io.Serializable; /** * Created by JIADONG on 16/4/29. */ public class Admin implements Serializable { private Integer id; private String account; private String password; private String token; private String lastLoginIp; public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastLoginIp() { return lastLoginIp; } public void setLastLoginIp(String lastLoginIp) { this.lastLoginIp = lastLoginIp; } @Override public String toString() { return "Admin{" + "id=" + id + ", account='" + account + '\'' + ", password='" + password + '\'' + ", token='" + token + '\'' + ", lastLoginIp='" + lastLoginIp + '\'' + '}'; } }
oGZo/zjgsu-abroadStu-web
backend/zjgsu-abroadStu/abroadStu-model/src/main/java/com/zjgsu/abroadStu/model/Admin.java
Java
bsd-2-clause
1,355
#include <string> #include <vector> #include <TH/TH.h> #include "caffe/caffe.hpp" extern "C" { void init(void* handle[1], const char* param_file, const char* model_file, const char* phase); void do_forward(void* handle[1], THFloatTensor* bottom, THFloatTensor* output); void do_backward(void* handle[1], THFloatTensor* gradOutput, THFloatTensor* gradInput); void reset(void* handle[1]); void set_mode_cpu(); void set_mode_gpu(); void set_phase_train(); void set_phase_test(); void set_device(int device_id); } using namespace caffe; // NOLINT(build/namespaces) void init(void* handle[1], const char* param_file, const char* model_file, const char* phase_name) { Phase phase; if (strcmp(phase_name, "train") == 0) { phase = TRAIN; } else if (strcmp(phase_name, "test") == 0) { phase = TEST; } else { THError("Unknown phase."); } Net<float>* net_ = new Net<float>(string(param_file), phase); if(model_file != NULL) net_->CopyTrainedLayersFrom(string(model_file)); handle[1] = net_; } void do_forward(void* handle[1], THFloatTensor* bottom, THFloatTensor* output) { Net<float>* net_ = (Net<float>*)handle[1]; const vector<Blob<float>*>& input_blobs = net_->input_blobs(); for (unsigned int i = 0; i < input_blobs.size(); ++i) { CHECK_EQ(bottom->size[0]*bottom->size[1]*bottom->size[2]*bottom->size[3], input_blobs[i]->count()) << "MatCaffe input size does not match the input size of the network"; const float* data_ptr = THFloatTensor_data(bottom); switch (Caffe::mode()) { case Caffe::CPU: caffe_copy(input_blobs[i]->count(), data_ptr, input_blobs[i]->mutable_cpu_data()); break; case Caffe::GPU: caffe_copy(input_blobs[i]->count(), data_ptr, input_blobs[i]->mutable_gpu_data()); break; default: LOG(FATAL) << "Unknown Caffe mode."; } // switch (Caffe::mode()) } const vector<Blob<float>*>& output_blobs = net_->ForwardPrefilled(); for (unsigned int i = 0; i < output_blobs.size(); ++i) { // internally data is stored as (width, height, channels, num) // where width is the fastest dimension THFloatTensor_resize4d(output, output_blobs[i]->num(), output_blobs[i]->channels(), output_blobs[i]->height(), output_blobs[i]->width()); float* data_ptr = THFloatTensor_data(output); switch (Caffe::mode()) { case Caffe::CPU: caffe_copy(output_blobs[i]->count(), output_blobs[i]->cpu_data(), data_ptr); break; case Caffe::GPU: caffe_copy(output_blobs[i]->count(), output_blobs[i]->gpu_data(), data_ptr); break; default: LOG(FATAL) << "Unknown Caffe mode."; } // switch (Caffe::mode()) } } void do_backward(void* handle[1], THFloatTensor* gradOutput, THFloatTensor* gradInput) { Net<float>* net_ = (Net<float>*)handle[1]; const vector<Blob<float>*>& output_blobs = net_->output_blobs(); const vector<Blob<float>*>& input_blobs = net_->input_blobs(); // First, copy the output diff for (unsigned int i = 0; i < output_blobs.size(); ++i) { const float* const data_ptr = THFloatTensor_data(gradOutput); switch (Caffe::mode()) { case Caffe::CPU: caffe_copy(output_blobs[i]->count(), data_ptr, output_blobs[i]->mutable_cpu_diff()); break; case Caffe::GPU: caffe_copy(output_blobs[i]->count(), data_ptr, output_blobs[i]->mutable_gpu_diff()); break; default: LOG(FATAL) << "Unknown Caffe mode."; } // switch (Caffe::mode()) } // LOG(INFO) << "Start"; net_->Backward(); // LOG(INFO) << "End"; for (unsigned int i = 0; i < input_blobs.size(); ++i) { // internally data is stored as (width, height, channels, num) // where width is the fastest dimension THFloatTensor_resize4d(gradInput, input_blobs[i]->num(), input_blobs[i]->channels(), input_blobs[i]->height(), input_blobs[i]->width()); float* data_ptr = THFloatTensor_data(gradInput); switch (Caffe::mode()) { case Caffe::CPU: caffe_copy(input_blobs[i]->count(), input_blobs[i]->cpu_diff(), data_ptr); break; case Caffe::GPU: caffe_copy(input_blobs[i]->count(), input_blobs[i]->gpu_diff(), data_ptr); break; default: LOG(FATAL) << "Unknown Caffe mode."; } // switch (Caffe::mode()) } } void read_mean(const char* mean_file_path, THFloatTensor* mean_tensor) { std::string mean_file(mean_file_path); Blob<float> data_mean; LOG(INFO) << "Loading mean file from" << mean_file; BlobProto blob_proto; bool result = ReadProtoFromBinaryFile(mean_file.c_str(), &blob_proto); data_mean.FromProto(blob_proto); THFloatTensor_resize4d(mean_tensor, data_mean.num(), data_mean.channels(), data_mean.height(), data_mean.width()); float* data_ptr = THFloatTensor_data(mean_tensor); caffe_copy(data_mean.count(), data_mean.cpu_data(), data_ptr); } void reset(void* handle[1]) { Net<float>* net_ = (Net<float>*)handle[1]; if (net_) { delete net_; LOG(INFO) << "Network reset, call init before use it again"; } } void set_mode_cpu() { Caffe::set_mode(Caffe::CPU); } void set_mode_gpu() { Caffe::set_mode(Caffe::GPU); } void set_device(int device_id) { Caffe::SetDevice(device_id); }
szagoruyko/torch-caffe-binding
caffe.cpp
C++
bsd-2-clause
5,255
package ChanteySongs.Data; import java.io.*; import java.util.*; import java.text.*; import com.thoughtworks.xstream.*; public class DataUtil { public static final DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); public static String getData(Scanner in, PrintWriter out, String name) { String tmp; out.print(name + ": "); out.flush(); tmp = in.nextLine(); return (tmp.length() == 0) ? null : tmp; } public static String getDataMultiLine(Scanner in, PrintWriter out, String name) { String tmp = ""; String ret = ""; out.print(name + ": "); out.flush(); while(!tmp.equalsIgnoreCase("end")) { ret += tmp + "\n"; tmp = in.nextLine(); } return (ret.replaceAll("\\s","").length() == 0) ? null : ret; } public static int getDataInt(Scanner in, PrintWriter out, String name) { String tmp; out.print(name + ": "); out.flush(); tmp = in.nextLine(); try { return (tmp.length() == 0) ? -1 : Integer.parseInt(tmp); }catch(NumberFormatException nfe) { System.err.println("Not an integer value for " + name + ": " + tmp); return -1; } } public static Date getDataDate(Scanner in, PrintWriter out, String name) { String tmp; out.print(name + ": "); out.flush(); tmp = in.nextLine(); try { return (tmp.length() == 0) ? null : formatter.parse(tmp); }catch(ParseException pe) { System.err.println("Could not parse date for " + name + ": " + tmp); return null; } } public static Set<String> getDataSet(Scanner in, PrintWriter out, String name) { Set<String> ret = new HashSet<String>(); String tmp; do { tmp = getData(in, out, name); if(tmp != null) { ret.add(tmp); } }while(tmp != null); return (ret.size() == 0)? null : ret; } public static void prepare(XStream xstream) { xstream.alias("Person", Person.class); xstream.alias("Index", Index.class); xstream.alias("Collection", SongCollection.class); xstream.alias("Song", Song.class); } }
wingerjc/ChanteySongs
source/java/ChanteySongs/Data/DataUtil.java
Java
bsd-2-clause
2,472
// -*- mode: C++ -*- // // Copyright (c) 2007, 2008, 2009, 2010, 2011 The University of Utah // All rights reserved. // // This file is part of `csmith', a random generator of C programs. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * 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. // // 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. #include <assert.h> #include <iostream> #include "CVQualifiers.h" #include "Type.h" #include "Effect.h" #include "CGContext.h" #include "CGOptions.h" #include "random.h" #include "Error.h" #include "Probabilities.h" #include "DepthSpec.h" #include "Enumerator.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CVQualifiers::CVQualifiers(void) : wildcard(false), accept_stricter(false) { // nothing else to do } CVQualifiers::CVQualifiers(bool wild, bool accept_stricter) : wildcard(wild), accept_stricter(accept_stricter) { // nothing else to do } CVQualifiers::CVQualifiers(const vector<bool>& isConsts, const vector<bool>& isVolatiles) : wildcard(false), accept_stricter(false), is_consts(isConsts), is_volatiles(isVolatiles) { // nothing else to do } CVQualifiers::CVQualifiers(const CVQualifiers &qfer) : wildcard(qfer.wildcard), accept_stricter(qfer.accept_stricter), is_consts(qfer.get_consts()), is_volatiles(qfer.get_volatiles()) { // nothing else to do } CVQualifiers::~CVQualifiers() { } CVQualifiers & CVQualifiers::operator=(const CVQualifiers &qfer) { if (this == &qfer) { return *this; } wildcard = qfer.wildcard; accept_stricter = qfer.accept_stricter; is_consts = qfer.get_consts(); is_volatiles = qfer.get_volatiles(); return *this; } // -------------------------------------------------------------- /* return true if this variable is more const-volatile qualified than v * some examples are: * const is more qualified than none * volatile is more qualified than none * const volatile is more qualified than const * const is NOT more qualified than volatile * ... * notice "const int**" is not convertable from "int**" * as explained in * http://www.embedded.com/columns/programmingpointers/180205632?_requestid=488055 **************************************************************/ bool CVQualifiers::stricter_than(const CVQualifiers& qfer) const { size_t i; assert(is_consts.size() == is_volatiles.size()); const vector<bool>& v_consts = qfer.get_consts(); const vector<bool>& v_volatiles = qfer.get_volatiles(); if (is_consts.size() != v_consts.size() || is_volatiles.size() != v_volatiles.size()) { return false; } size_t depth = is_consts.size(); // check "const" qualifier first for (i=0; i<depth; i++) { // for special rule: "const int**" is not convertable from "int**" // actually for a level that is followed by two "*"s, we have to match // "const" qualifier if (depth - i > 2 && is_consts[i] != v_consts[i]) { return false; } if (v_consts[i] && !is_consts[i]) { return false; } } // check "volatile" qualifier second // special rule: the volatile property on storage (1st in vector) must match // can be relaxed??? if (depth > 1 && is_volatiles[0] != v_volatiles[0]) { return false; } for (i=0; i<depth; i++) { // similiar to const: "volatile int**" is not convertable from "int**" // actually for a level that is followed by two "*"s, we have to match if (depth - i > 2 && is_volatiles[i] != v_volatiles[i]) { return false; } if (v_volatiles[i] && !is_volatiles[i]) { return false; } } return true; } bool CVQualifiers::match(const CVQualifiers& qfer) const { if (wildcard) { return true; } if (CGOptions::match_exact_qualifiers()) { return is_consts == qfer.get_consts() && is_volatiles == qfer.get_volatiles(); } // return true if both variables are non-pointer (has only one level qualifier) if (is_consts.size() == qfer.get_consts().size() && is_consts.size()==1) { assert(is_consts.size() == is_volatiles.size()); return true; } return (!accept_stricter && stricter_than(qfer)) || (accept_stricter && qfer.stricter_than(*this)); } bool CVQualifiers::match_indirect(const CVQualifiers& qfer) const { if (wildcard) { return true; } if (is_consts.size() == qfer.get_consts().size()) { return match(qfer); } int deref = qfer.get_consts().size() - is_consts.size(); if (deref < -1) { return false; } return match(qfer.indirect_qualifiers(deref)); } /* * make sure no volatile-pointers if volatile-pointers is false */ void CVQualifiers::make_scalar_volatiles(std::vector<bool> &volatiles) { if (!CGOptions::volatile_pointers()) { for (size_t i=1; i<volatiles.size(); i++) volatiles[i] = false; } } /* * make sure no const-pointers if const_pointers is false */ void CVQualifiers::make_scalar_consts(std::vector<bool> &consts) { if (!CGOptions::const_pointers()) { for (size_t i=1; i<consts.size(); i++) consts[i] = false; } } /* * generate a random CV qualifier vector that is looser or stricter than this one */ CVQualifiers CVQualifiers::random_qualifiers(bool no_volatile, Effect::Access access, const CGContext &cg_context) const { std::vector<bool> volatiles; std::vector<bool> consts; if (wildcard) { return CVQualifiers(true, accept_stricter); } // use non-volatile for all levels if requested if (no_volatile) { for (size_t i=0; i<is_volatiles.size(); i++) { volatiles.push_back(false); } } else { volatiles = !accept_stricter ? random_looser_volatiles() : random_stricter_volatiles(); ERROR_GUARD(CVQualifiers(consts, volatiles)); if (!cg_context.get_effect_context().is_side_effect_free()) { volatiles[volatiles.size() - 1] = false; } } ERROR_GUARD(CVQualifiers(consts, volatiles)); make_scalar_volatiles(volatiles); consts = !accept_stricter ? random_looser_consts() : random_stricter_consts(); make_scalar_consts(consts); ERROR_GUARD(CVQualifiers(consts, volatiles)); if (access == Effect::WRITE) { consts[consts.size() - 1] = false; } return CVQualifiers(consts, volatiles); } /* * generate a random CV qualifier vector that is looser than this one */ CVQualifiers CVQualifiers::random_loose_qualifiers(bool no_volatile, Effect::Access access, const CGContext &cg_context) const { std::vector<bool> volatiles; std::vector<bool> consts; if (wildcard) { return CVQualifiers(true, accept_stricter); } // use non-volatile for all levels if requested if (no_volatile) { for (size_t i=0; i<is_volatiles.size(); i++) { volatiles.push_back(false); } } else { volatiles = random_looser_volatiles(); ERROR_GUARD(CVQualifiers(consts, volatiles)); if (!cg_context.get_effect_context().is_side_effect_free()) { volatiles[volatiles.size() - 1] = false; } } ERROR_GUARD(CVQualifiers(consts, volatiles)); make_scalar_volatiles(volatiles); consts = random_looser_consts(); make_scalar_consts(consts); ERROR_GUARD(CVQualifiers(consts, volatiles)); if (access == Effect::WRITE) { consts[consts.size() - 1] = false; } return CVQualifiers(consts, volatiles); } CVQualifiers CVQualifiers::random_qualifiers(const Type* t, Effect::Access access, const CGContext &cg_context, bool no_volatile) { return random_qualifiers(t, access, cg_context, no_volatile, RegularConstProb, RegularVolatileProb); } CVQualifiers CVQualifiers::random_qualifiers(const Type* t, Effect::Access access, const CGContext &cg_context, bool no_volatile, unsigned int const_prob, unsigned int volatile_prob) { CVQualifiers ret_qfer; if (t==0) { return ret_qfer; } bool isVolatile = false; bool isConst = false; std::vector<bool> is_consts, is_volatiles; const Effect &effect_context = cg_context.get_effect_context(); // set random volatile/const properties for each level of indirection for pointers const Type* tmp = t->ptr_type; while (tmp) { DEPTH_GUARD_BY_DEPTH_RETURN(2, ret_qfer); isVolatile = rnd_flipcoin(volatile_prob); ERROR_GUARD(ret_qfer); isConst = rnd_flipcoin(const_prob); ERROR_GUARD(ret_qfer); if (isVolatile && isConst && !CGOptions::allow_const_volatile()) { isConst = false; } is_consts.push_back(isConst); is_volatiles.push_back(isVolatile); tmp = tmp->ptr_type; } // set random volatile/const properties for variable itself bool volatile_ok = effect_context.is_side_effect_free(); bool const_ok = (access != Effect::WRITE); isVolatile = false; isConst = false; if (volatile_ok && const_ok) { DEPTH_GUARD_BY_DEPTH_RETURN(2, ret_qfer); isVolatile = rnd_flipcoin(volatile_prob); ERROR_GUARD(ret_qfer); isConst = rnd_flipcoin(const_prob); ERROR_GUARD(ret_qfer); } else if (volatile_ok) { DEPTH_GUARD_BY_DEPTH_RETURN(1, ret_qfer); isVolatile = rnd_flipcoin(volatile_prob); ERROR_GUARD(ret_qfer); } else if (const_ok) { DEPTH_GUARD_BY_DEPTH_RETURN(1, ret_qfer); isConst = rnd_flipcoin(const_prob); ERROR_GUARD(ret_qfer); } if (isVolatile && isConst && !CGOptions::allow_const_volatile()) { isConst = false; } is_consts.push_back(isConst); is_volatiles.push_back(isVolatile); // use non-volatile for all levels if requested if (no_volatile) { for (size_t i=0; i<is_volatiles.size(); i++) { is_volatiles[i] = false; } } make_scalar_volatiles(is_volatiles); make_scalar_consts(is_consts); return CVQualifiers(is_consts, is_volatiles); } /* * make a random qualifier for type t, assuming non context, * and no volatile allowed */ CVQualifiers CVQualifiers::random_qualifiers(const Type* t) { return random_qualifiers(t, Effect::READ, CGContext::get_empty_context(), true); } /* * be careful to use it because it will generate volatile without knowing the context. * Only used to generate qulifiers for struct/unions */ CVQualifiers CVQualifiers::random_qualifiers(const Type* t, unsigned int const_prob, unsigned int volatile_prob) { return random_qualifiers(t, Effect::READ, CGContext::get_empty_context(), false, const_prob, volatile_prob); } vector<bool> CVQualifiers::random_stricter_consts(void) const { vector<bool> consts; size_t i; size_t depth = is_consts.size(); if (CGOptions::match_exact_qualifiers()) return is_consts; for (i=0; i<depth; i++) { // special case // const int** is not stricter than int** // int * const ** is not stricter than int*** // and so on... if (is_consts[i] || (depth - i > 2)) { consts.push_back(is_consts[i]); } else if (is_volatiles[i] && !CGOptions::allow_const_volatile()) { consts.push_back(false); } else { DEPTH_GUARD_BY_DEPTH_RETURN(1, consts); bool index = rnd_flipcoin(StricterConstProb); ERROR_GUARD(consts); consts.push_back(index); } } return consts; } vector<bool> CVQualifiers::random_stricter_volatiles(void) const { vector<bool> volatiles; size_t i; size_t depth = is_volatiles.size(); if (CGOptions::match_exact_qualifiers()) return is_volatiles; for (i=0; i<depth; i++) { // first one (storage must match, any level followed by at least two more // indirections must match if (is_volatiles[i] || (i==0 && depth>1) || (depth - i > 2)) { volatiles.push_back(is_volatiles[i]); } else if (is_consts[i] && !CGOptions::allow_const_volatile()) { volatiles.push_back(false); } else { DEPTH_GUARD_BY_DEPTH_RETURN(1, volatiles); bool index = rnd_flipcoin(RegularVolatileProb); ERROR_GUARD(volatiles); volatiles.push_back(index); } } make_scalar_volatiles(volatiles); return volatiles; } vector<bool> CVQualifiers::random_looser_consts(void) const { vector<bool> consts; size_t i; size_t depth = is_consts.size(); if (CGOptions::match_exact_qualifiers()) return is_consts; for (i=0; i<depth; i++) { // special case if (!is_consts[i] || (depth - i > 2)) { consts.push_back(is_consts[i]); } else { DEPTH_GUARD_BY_DEPTH_RETURN(1, consts); bool index = rnd_flipcoin(LooserConstProb); ERROR_GUARD(consts); consts.push_back(index); } } return consts; } vector<bool> CVQualifiers::random_looser_volatiles(void) const { vector<bool> volatiles; size_t i; size_t depth = is_volatiles.size(); if (CGOptions::match_exact_qualifiers()) return is_volatiles; for (i=0; i<depth; i++) { if (!is_volatiles[i] || (i==0 && depth>1) || (depth - i > 2)) { volatiles.push_back(is_volatiles[i]); } else { DEPTH_GUARD_BY_DEPTH_RETURN(1, volatiles); bool index = rnd_flipcoin(RegularVolatileProb); ERROR_GUARD(volatiles); volatiles.push_back(index); } } make_scalar_volatiles(volatiles); return volatiles; } void CVQualifiers::add_qualifiers(bool is_const, bool is_volatile) { is_consts.push_back(is_const); is_volatiles.push_back(is_volatile); } // actually add qualifiers to pointers CVQualifiers CVQualifiers::random_add_qualifiers(bool no_volatile) const { CVQualifiers qfer = *this; if (CGOptions::match_exact_qualifiers()) { qfer.add_qualifiers(false, false); return qfer; } //bool is_const = rnd_upto(50); if (no_volatile) { DEPTH_GUARD_BY_DEPTH_RETURN(1, qfer); } else { DEPTH_GUARD_BY_DEPTH_RETURN(2, qfer); } bool is_const; if (!CGOptions::const_pointers()) is_const = false; else is_const = rnd_flipcoin(RegularConstProb); ERROR_GUARD(qfer); //bool is_volatile = no_volatile ? false : rnd_upto(RegularVolatileProb); bool is_volatile; if (no_volatile || !CGOptions::volatile_pointers()) is_volatile = false; else is_volatile = rnd_flipcoin(RegularVolatileProb); ERROR_GUARD(qfer); qfer.add_qualifiers(is_const, is_volatile); return qfer; } void CVQualifiers::remove_qualifiers(int len) { int i; for (i=0; i<len; i++) { is_consts.pop_back(); is_volatiles.pop_back(); } } CVQualifiers CVQualifiers::indirect_qualifiers(int level) const { if (level == 0 || wildcard) { return *this; } // taking address else if (level < 0) { assert(level == -1); CVQualifiers qfer = *this; qfer.add_qualifiers(false, false); return qfer; } // dereference else { CVQualifiers qfer = *this; qfer.remove_qualifiers(level); return qfer; } } /* * check if the indirect depth of type matches qualifier size */ bool CVQualifiers::sanity_check(const Type* t) const { assert(t); int level = t->get_indirect_level(); assert(level >= 0); return wildcard || (is_consts.size() == is_volatiles.size() && (static_cast<size_t>(level)+1) == is_consts.size()); } void CVQualifiers::output_qualified_type(const Type* t, std::ostream &out) const { assert(t); assert(sanity_check(t)); size_t i; const Type* base = t->get_base_type(); for (i=0; i<is_consts.size(); i++) { if (i>0) { out << "*"; } if (is_consts[i]) { if (!CGOptions::consts()) assert(0); if (i > 0) out << " "; out << "const "; } if (is_volatiles[i]) { if (!CGOptions::volatiles()) assert(0); if (i > 0) out << " "; out << "volatile "; } if (i==0) { base->Output(out); out << " "; } } } void CVQualifiers::output_qualified_type_with_deputy_annotation(const Type* t, std::ostream &out, const vector<string>& annotations) const { assert(t); assert(sanity_check(t)); assert(is_consts.size() == annotations.size()+1); size_t i; const Type* base = t->get_base_type(); for (i=0; i<is_consts.size(); i++) { if (i>0) { out << "* "; out << annotations[i-1] << " "; } if (is_consts[i]) { if (!CGOptions::consts()) assert(0); out << "const "; } if (is_volatiles[i]) { if (!CGOptions::volatiles()) assert(0); out << "volatile "; } if (i==0) { base->Output(out); out << " "; } } } bool CVQualifiers::is_const_after_deref(int deref_level) const { if (deref_level < 0) { return false; } size_t len = is_consts.size(); assert(len > static_cast<size_t>(deref_level)); return is_consts[len - deref_level - 1]; } bool CVQualifiers::is_volatile_after_deref(int deref_level) const { if (deref_level < 0) { return false; } size_t len = is_volatiles.size(); assert(len > static_cast<size_t>(deref_level)); /* if (len <= static_cast<size_t>(deref_level)) { cout << "len = " << len << ", deref_level = " << deref_level << std::endl; assert(0); } */ return is_volatiles[len - deref_level - 1]; } void CVQualifiers::set_const(bool is_const, int pos) { int len = is_consts.size(); if (len > 0) { is_consts[len - pos - 1] = is_const; } } void CVQualifiers::set_volatile(bool is_volatile, int pos) { int len = is_volatiles.size(); if (len > 0) { is_volatiles[len - pos - 1] = is_volatile; } } void CVQualifiers::restrict(Effect::Access access, const CGContext& cg_context) { if (access == Effect::WRITE) { set_const(false); } if (!cg_context.get_effect_context().is_side_effect_free()) { set_volatile(false); } } /* * For now, only used to generate all qualifiers for struct fields. * Also, since we don't support fields with pointer types, we only * enumerate the first level of qualifiers. */ void CVQualifiers::get_all_qualifiers(vector<CVQualifiers> &quals, unsigned int const_prob, unsigned int volatile_prob) { Enumerator<string> qual_enumerator; qual_enumerator.add_bool_elem("const_prob", const_prob); qual_enumerator.add_bool_elem("volatile_prob", volatile_prob); Enumerator<string> *i; for (i = qual_enumerator.begin(); i != qual_enumerator.end(); i = i->next()) { bool isConst = i->get_elem("const_prob"); bool isVolatile = i->get_elem("volatile_prob"); vector<bool> consts; vector<bool> volatiles; consts.push_back(isConst); volatiles.push_back(isVolatile); CVQualifiers qual(consts, volatiles); quals.push_back(qual); } } void CVQualifiers::OutputFirstQuals(std::ostream &out) const { if (is_consts.size() > 0 && is_consts[0]) { if (!CGOptions::consts()) assert(0); out << "const "; } if (is_volatiles.size() > 0 && is_volatiles[0]) { if (!CGOptions::volatiles()) assert(0); out << "volatile "; } } void CVQualifiers::output() const { size_t i; for (i=0; i<is_consts.size(); i++) { cout << is_consts[i] << " "; } cout << ", "; for (i=0; i<is_volatiles.size(); i++) { cout << is_volatiles[i] << " "; } cout << endl; }
ChrisLidbury/CLSmith
src/CVQualifiers.cpp
C++
bsd-2-clause
19,286
/*****************************************************************************/ /* */ /* RobotIRC 0.1.2 */ /* Copyright (c) 2013-2017, Frederic Cambus */ /* https://github.com/fcambus/robotirc */ /* */ /* Created: 2013-12-17 */ /* Last Updated: 2017-02-03 */ /* */ /* RobotIRC is released under the BSD 2-Clause license. */ /* See LICENSE file for details. */ /* */ /*****************************************************************************/ var crypto = require('crypto'); var dns = require('dns'); var net = require('net'); /**[ NPM Modules ]************************************************************/ var alexa = require('alexarank'); var irc = require('irc'); var log = require('npmlog'); var request = require('request'); /**[ RobotIRC ]***************************************************************/ module.exports = function(config) { var client = new irc.Client(config.server, config.nickname, config.options); /**[ Connection ]*********************************************************/ client.addListener('registered', function(message) { log.info("", "RobotIRC is now connected to " + config.server); }); /**[ Error handler ]******************************************************/ client.addListener('error', function(message) { log.error("", message.args.splice(1, message.args.length).join(" - ")); }); /**[ CTCP VERSION handler ]***********************************************/ client.addListener('ctcp-version', function(from, to, message) { client.ctcp(from, 'notice', "VERSION " + config.options.realName); }); /**[ Message handler ]****************************************************/ client.addListener('message', function(from, to, message) { var params = message.split(' ').slice(1).join(' '); if (to == client.nick) { // Handling private messages to = from; } /**********************************************************[ !help ]**/ if (message.match(/^!help/)) { var help = "RobotIRC 0.1.2 supports the following commands:\n" + "!alexa => Get Alexa traffic rank for a domain or URL\n" + "!date => Display server local time\n" + "!expand => Expand a shortened URL\n" + "!headers => Display HTTP headers for queried URL\n" + "!resolve => Get A records (IPv4) and AAAA records (IPv6) for queried domain\n" + "!reverse => Get reverse (PTR) records from IPv4 or IPv6 addresses\n" + "!wikipedia => Query Wikipedia for an article summary\n"; client.say(to, help); } /*********************************************************[ !alexa ]**/ if (message.match(/^!alexa/)) { alexa(params, function(error, result) { if (!error && typeof result.rank != "undefined") { client.say(to, "Alexa Traffic Rank for " + result.idn.slice(0, -1) + ": " + result.rank); } }); } /**********************************************************[ !date ]**/ if (message.match(/^!date/)) { client.say(to, Date()); } /********************************************************[ !expand ]**/ if (message.match(/^!expand/)) { request({ method: "HEAD", url: params, followAllRedirects: true }, function(error, response) { if (!error && response.statusCode == 200) { client.say(to, response.request.href); } }); } /*******************************************************[ !headers ]**/ if (message.match(/^!headers/)) { request(params, function(error, response, body) { if (!error && response.statusCode == 200) { for (var item in response.headers) { client.say(to, item + ": " + response.headers[item] + "\n"); } } }); } /*******************************************************[ !resolve ]**/ if (message.match(/^!resolve/)) { dns.resolve4(params, function(error, addresses) { if (!error) { for (var item in addresses) { client.say(to, addresses[item] + "\n"); } } dns.resolve6(params, function(error, addresses) { if (!error) { for (var item in addresses) { client.say(to, addresses[item] + "\n"); } } }); }); } /*******************************************************[ !reverse ]**/ if (message.match(/^!reverse/)) { if (net.isIP(params)) { dns.reverse(params, function(error, domains) { if (!error) { client.say(to, domains[0]); } }); } } /*****************************************************[ !wikipedia ]**/ if (message.match(/^!wikipedia/)) { params.split(' ').join('_'); dns.resolveTxt(params + ".wp.dg.cx", function(error, txt) { if (!error) { client.say(to, txt[0]); } }); } }); };
fcambus/robotirc
lib/robotirc.js
JavaScript
bsd-2-clause
6,242
/* * This file is released under terms of BSD license * See LICENSE file for more information * @author Mikhail Zhigun */ package clawfc.depscan; import java.io.InputStream; import javax.xml.XMLConstants; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import clawfc.Configuration; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.Unmarshaller; public class FortranFileProgramUnitInfoDeserializer { final Unmarshaller _unmarshaller; final String SCHEMA_FILE = "/clawfc/depscan/serial/file_unit_info.xsd"; public FortranFileProgramUnitInfoDeserializer(boolean validate) throws Exception { JAXBContext contextObj = JAXBContext.newInstance(clawfc.depscan.serial.FortranFileProgramUnitInfo.class); _unmarshaller = contextObj.createUnmarshaller(); if (validate) { Schema schema; try (InputStream schemaStream = Configuration.class.getResourceAsStream(SCHEMA_FILE)) { SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schema = sf.newSchema(new StreamSource(schemaStream)); } _unmarshaller.setSchema(schema); } } public clawfc.depscan.FortranFileProgramUnitInfo deserialize(InputStream in) throws Exception { FortranFileProgramUnitInfo deObj = new FortranFileProgramUnitInfo( (clawfc.depscan.serial.FortranFileProgramUnitInfo) _unmarshaller.unmarshal(in)); return deObj; } }
clementval/claw-compiler
driver/src/clawfc/depscan/FortranFileProgramUnitInfoDeserializer.java
Java
bsd-2-clause
1,597
<?php class Kwf_Assets_Provider_Components extends Kwf_Assets_Provider_Abstract { private $_rootComponentClass; private $_componentFiles = array(); public function __construct($rootComponentClass) { $this->_rootComponentClass = $rootComponentClass; } private function _createDependencyForFile($file) { if (!isset($this->_componentFiles[$file])) { $this->_componentFiles[$file] = Kwf_Assets_Dependency_File::createDependency($file, $this->_providerList); $this->_componentFiles[$file]->setIsCommonJsEntry(true); } return $this->_componentFiles[$file]; } public function getDependency($dependencyName) { if ($dependencyName == 'Components') { $ret = array(); $nonDeferDep = array(); $files = Kwf_Component_Abstract_Admin::getComponentFiles($this->_rootComponentClass, array( 'css' => array('filename'=>'Web', 'ext'=>'css', 'returnClass'=>false, 'multiple'=>true), 'printcss' => array('filename'=>'Web', 'ext'=>'printcss', 'returnClass'=>false, 'multiple'=>true), 'scss' => array('filename'=>'Web', 'ext'=>'scss', 'returnClass'=>false, 'multiple'=>true), )); foreach ($files as $i) { foreach ($i as $j) { $cwd = str_replace(DIRECTORY_SEPARATOR, '/', getcwd()); if (substr($j, 0, 3) == '../') { $cwd = substr($cwd, 0, strrpos($cwd, '/')); $j = substr($j, 3); } $j = $cwd.'/'.$j; $jj = Kwf_Assets_Dependency_File::getPathWithTypeByFileName($j); if (!$jj) { throw new Kwf_Exception("Can't find path type for '$j'"); } $nonDeferDep[] = $this->_createDependencyForFile($jj); } } if ($nonDeferDep) { $nonDeferDep = new Kwf_Assets_Dependency_Dependencies($nonDeferDep, 'Web'); $ret[] = $nonDeferDep; } $componentClasses = $this->_getRecursiveChildClasses($this->_rootComponentClass); foreach ($componentClasses as $class) { $nonDeferDep = $this->_getComponentSettingDependencies($class, 'assets'); $deferDep = $this->_getComponentSettingDependencies($class, 'assetsDefer'); //alle dateien der vererbungshierache includieren $files = Kwc_Abstract::getSetting($class, 'componentFiles'); $componentCssFiles = array(); foreach (array_merge($files['css'], $files['printcss'], $files['js'], $files['masterCss']) as $f) { $componentCssFiles[] = $f; } //reverse damit css von weiter unten in der vererbungshierachie überschreibt $componentCssFiles = array_reverse($componentCssFiles); foreach ($componentCssFiles as $i) { $i = getcwd().'/'.$i; $i = Kwf_Assets_Dependency_File::getPathWithTypeByFileName($i); if (!isset($this->_componentFiles[$i])) { $addedFiles[] = $i; $dep = $this->_createDependencyForFile($i); if (substr($i, -8) == 'defer.js') { $deferDep[] = $dep; } else { $nonDeferDep[] = $dep; } } } if ($deferDep) { $deferDep = new Kwf_Assets_Dependency_Dependencies($deferDep, $class.' defer'); $deferDep->setDeferLoad(true); $ret[] = $deferDep; } if ($nonDeferDep) { $nonDeferDep = new Kwf_Assets_Dependency_Dependencies($nonDeferDep, $class); $ret[] = $nonDeferDep; } } return new Kwf_Assets_Dependency_Dependencies($ret, $dependencyName); } else if ($dependencyName == 'ComponentsAdmin') { $ret = array(); $componentClasses = $this->_getRecursiveChildClasses($this->_rootComponentClass); foreach ($componentClasses as $class) { $ret = array_merge($ret, $this->_getComponentSettingDependencies($class, 'assetsAdmin')); } return new Kwf_Assets_Dependency_Dependencies($ret, $dependencyName); } return null; } private function _getComponentSettingDependencies($class, $setting) { $ret = array(); $assets = Kwc_Abstract::getSetting($class, $setting); if (!is_array($assets['dep'])) { throw new Kwf_Exception("Invalid dep dependency for '$class'"); } foreach ($assets['dep'] as $i) { $d = $this->_providerList->findDependency(trim($i)); if (!$d) { throw new Kwf_Exception("Can't find dependency '$i'"); } $ret[] = $d; } foreach ($assets['files'] as $i) { if (!is_object($i)) { $i = $this->_createDependencyForFile($i); } $ret[] = $i; } return $ret; } private function _getRecursiveChildClasses($class, &$processedComponents = array()) { $processedComponents[] = $class; $ret = array(); $ret[] = $class; $classes = Kwc_Abstract::getChildComponentClasses($class); $classes = array_merge($classes, Kwc_Abstract::getSetting($class, 'plugins')); foreach (Kwc_Abstract::getSetting($class, 'generators') as $g) { if (isset($g['plugins'])) { $classes = array_merge($classes, $g['plugins']); } } foreach ($classes as $i) { if ($i && !in_array($i, $processedComponents)) { $ret = array_merge($ret, $this->_getRecursiveChildClasses($i, $processedComponents)); } } return $ret; } }
nsams/koala-framework
Kwf/Assets/Provider/Components.php
PHP
bsd-2-clause
6,174
# -*- coding: utf-8 -*- import os import requests import time import math import datetime import random import envoy import jsonfield import logging import urllib from collections import defaultdict from magic_repr import make_repr from hashlib import md5, sha1 from django.db import models from django.db.models import Q from django.utils import timezone from django.conf import settings from django.contrib.auth.models import AbstractBaseUser, UserManager as BaseUserManager from django.core.cache import cache #from south.modelsinspector import add_introspection_rules from twiggy_goodies.threading import log from allmychanges.validators import URLValidator from allmychanges.downloaders.utils import normalize_url from allmychanges.issues import calculate_issue_importance from allmychanges.utils import ( split_filenames, parse_search_list, get_one_or_none, ) from allmychanges import chat from allmychanges.downloaders import ( get_downloader) from allmychanges.utils import reverse from allmychanges.tasks import ( update_preview_task, update_changelog_task) from allmychanges.exceptions import SynonymError MARKUP_CHOICES = ( ('markdown', 'markdown'), ('rest', 'rest'), ) NAME_LENGTH = 80 NAMESPACE_LENGTH = 80 DESCRIPTION_LENGTH = 255 PROCESSING_STATUS_LENGTH = 40 # based on http://www.caktusgroup.com/blog/2013/08/07/migrating-custom-user-model-django/ from pytz import common_timezones TIMEZONE_CHOICES = [(tz, tz) for tz in common_timezones] class URLField(models.URLField): default_validators = [URLValidator()] #add_introspection_rules([], ["^allmychanges\.models\.URLField"]) class UserManager(BaseUserManager): def _create_user(self, username, email=None, password=None, **extra_fields): now = timezone.now() email = self.normalize_email(email) user = self.model(username=username, email=email, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create(self, *args, **kwargs): email = kwargs.get('email') if email and self.filter(email=email).count() > 0: raise ValueError('User with email "{0}" already exists'.format(email)) username = kwargs.get('username') url = settings.BASE_URL + reverse('admin-user-profile', username=username) chat.send(('New user <{url}|{username}> ' 'with email "{email}" (from create)').format( url=url, username=username, email=email)) return super(UserManager, self).create(*args, **kwargs) def create_user(self, username, email=None, password=None, **extra_fields): if email and self.filter(email=email).count() > 0: raise ValueError('User with email "{0}" already exists'.format(email)) url = settings.BASE_URL + reverse('admin-user-profile', username=username) chat.send(('New user <{url}|{username}> ' 'with email "{email}" (from create_user)').format( url=url, username=username, email=email)) return self._create_user(username, email, password, **extra_fields) def active_users(self, interval): """Outputs only users who was active in last `interval` days. """ after = timezone.now() - datetime.timedelta(interval) queryset = self.all() queryset = queryset.filter(history_log__action__in=ACTIVE_USER_ACTIONS, history_log__created_at__gte=after).distinct() return queryset SEND_DIGEST_CHOICES = ( ('daily', 'Every day'), ('weekly', 'Every week (on Monday)'), ('never', 'Never')) RSS_HASH_LENGH = 32 class User(AbstractBaseUser): """ A fully featured User model with admin-compliant permissions that uses a full-length email field as the username. Email and password are required. Other fields are optional. """ username = models.CharField('user name', max_length=254, unique=True) email = models.EmailField('email address', max_length=254) email_is_valid = models.BooleanField(default=False) date_joined = models.DateTimeField('date joined', default=timezone.now) timezone = models.CharField(max_length=100, choices=TIMEZONE_CHOICES, default='UTC') changelogs = models.ManyToManyField('Changelog', through='ChangelogTrack', related_name='trackers') feed_versions = models.ManyToManyField('Version', through='FeedItem', related_name='users') feed_sent_id = models.IntegerField( default=0, help_text='Keeps position in feed items already sent in digest emails') last_digest_sent_at = models.DateTimeField( blank=True, null=True, help_text='Date when last email digest was sent') skips_changelogs = models.ManyToManyField('Changelog', through='ChangelogSkip', related_name='skipped_by') moderated_changelogs = models.ManyToManyField('Changelog', through='Moderator', related_name='moderators') # notification settings send_digest = models.CharField(max_length=100, choices=SEND_DIGEST_CHOICES, default='daily') slack_url = models.URLField(max_length=2000, default='', blank=True) webhook_url = models.URLField(max_length=2000, default='', blank=True) rss_hash = models.CharField(max_length=RSS_HASH_LENGH, unique=True, blank=True, null=True) custom_fields = jsonfield.JSONField( default={}, help_text='Custom fields such like "Location" or "SecondEmail".', blank=True) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] class Meta: verbose_name = 'user' verbose_name_plural = 'users' __repr__ = make_repr('username', 'email') def get_avatar(self, size): # adorable_template = 'https://api.adorable.io/avatars/{size}/{hash}.png' robohash_template = 'https://robohash.org/{hash}.png?size={size}x{size}' if self.email: hash = md5(self.email.lower()).hexdigest() default = robohash_template.format(size=size, hash=hash) avatar_url = 'https://www.gravatar.com/avatar/{hash}?{opts}'.format( hash=hash, opts=urllib.urlencode( dict( s=str(size), d=default ) ) ) else: hash = md5(self.username).hexdigest() avatar_url = robohash_template.format(size=size, hash=hash) return avatar_url @property def is_superuser(self): return self.username in settings.SUPERUSERS def does_track(self, changelog): """Check if this user tracks given changelog.""" return self.changelogs.filter(pk=changelog.id).exists() def track(self, changelog): if not self.does_track(changelog): if changelog.namespace == 'web' and changelog.name == 'allmychanges': action = 'track-allmychanges' action_description = 'User tracked our project\'s changelog.' else: action = 'track' action_description = 'User tracked changelog:{0}'.format(changelog.id) UserHistoryLog.write(self, '', action, action_description) ChangelogTrack.objects.create( user=self, changelog=changelog) def untrack(self, changelog): if self.does_track(changelog): if changelog.namespace == 'web' and changelog.name == 'allmychanges': action = 'untrack-allmychanges' action_description = 'User untracked our project\'s changelog.' else: action = 'untrack' action_description = 'User untracked changelog:{0}'.format(changelog.id) UserHistoryLog.write(self, '', action, action_description) ChangelogTrack.objects.filter( user=self, changelog=changelog).delete() def does_skip(self, changelog): """Check if this user skipped this changelog in package selector.""" return self.skips_changelogs.filter(pk=changelog.id).exists() def skip(self, changelog): if not self.does_skip(changelog): action = 'skip' action_description = 'User skipped changelog:{0}'.format(changelog.id) UserHistoryLog.write(self, '', action, action_description) ChangelogSkip.objects.create( user=self, changelog=changelog) def add_feed_item(self, version): if self.send_digest == 'never': return None return FeedItem.objects.create(user=self, version=version) def save(self, *args, **kwargs): if self.rss_hash is None: self.rss_hash = sha1(self.username + settings.SECRET_KEY).hexdigest()[:RSS_HASH_LENGH] return super(User, self).save(*args, **kwargs) class Subscription(models.Model): email = models.EmailField() come_from = models.CharField(max_length=100) date_created = models.DateTimeField() def __unicode__(self): return self.email class Downloadable(object): """Adds method download, which uses attribute `source` to update attribute `downloader` if needed and then to download repository into a temporary directory. """ def download(self, downloader, report_back=lambda message, level=logging.INFO: None): """This method fetches repository into a temporary directory and returns path to this directory. It can report about downloading status using callback `report_back`. Everything what will passed to `report_back`, will be displayed to the end user in a processing log on a "Tune" page. """ if isinstance(downloader, dict): params = downloader.get('params', {}) downloader = downloader['name'] else: params = {} params.update(self.downloader_settings or {}) download = get_downloader(downloader) return download(self.source, report_back=report_back, **params) # A mixin to get/set ignore and check lists on a model. def get_ignore_list(self): """Returns a list with all filenames and directories to ignore when searching a changelog.""" return split_filenames(self.ignore_list) def set_ignore_list(self, items): self.ignore_list = u'\n'.join(items) def get_search_list(self): """Returns a list with all filenames and directories to check when searching a changelog.""" return parse_search_list(self.search_list) def set_search_list(self, items): def process(item): if isinstance(item, tuple) and item[1]: return u':'.join(item) else: return item self.search_list = u'\n'.join(map(process, items)) class ChangelogManager(models.Manager): def only_active(self): # active changelog is good and not paused queryset = self.good() return queryset.filter(paused_at=None) def good(self): # good changelog should have namespace, name, source and downloader return self.all().exclude( Q(name=None) | Q(namespace=None) | Q(downloader=None) | Q(source='')) def unsuccessful(self): return self.all().filter( Q(name=None) | Q(namespace=None) | Q(downloader=None) | Q(source='')) class Changelog(Downloadable, models.Model): objects = ChangelogManager() source = URLField(db_index=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) # TODO: remove processing_started_at = models.DateTimeField(blank=True, null=True) problem = models.CharField(max_length=1000, help_text='Latest error message', blank=True, null=True) # TODO: remove filename = models.CharField(max_length=1000, help_text=('If changelog was discovered, then ' 'field will store it\'s filename'), blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) next_update_at = models.DateTimeField(default=timezone.now) paused_at = models.DateTimeField(blank=True, null=True) last_update_took = models.IntegerField( help_text=('Number of seconds required to ' 'update this changelog last time'), default=0) ignore_list = models.CharField(max_length=1000, default='', help_text=('Comma-separated list of directories' ' and filenames to ignore searching' ' changelog.'), blank=True) # TODO: выяснить зачем тут два поля check_list и search_list check_list = models.CharField(max_length=1000, default='', help_text=('Comma-separated list of directories' ' and filenames to search' ' changelog.'), blank=True) search_list = models.CharField(max_length=1000, default='', help_text=('Comma-separated list of directories' ' and filenames to search' ' changelog.'), blank=True) xslt = models.TextField(default='', help_text=('XSLT transform to be applied to all html files.'), blank=True) namespace = models.CharField(max_length=NAMESPACE_LENGTH, blank=True, null=True) name = models.CharField(max_length=NAME_LENGTH, blank=True, null=True) description = models.CharField(max_length=DESCRIPTION_LENGTH, blank=True, default='') downloader = models.CharField(max_length=20, blank=True, null=True) downloader_settings = jsonfield.JSONField( default={}, help_text=('JSON with settings for selected downloader.'), blank=True) downloaders = jsonfield.JSONField( default=[], help_text=('JSON with guessed downloaders and their additional meta information.'), blank=True) status = models.CharField(max_length=40, default='created') processing_status = models.CharField(max_length=PROCESSING_STATUS_LENGTH) icon = models.CharField(max_length=1000, blank=True, null=True) class Meta: unique_together = ('namespace', 'name') def __unicode__(self): return u'Changelog from {0}'.format(self.source) __repr__ = make_repr('namespace', 'name', 'source') def latest_versions(self, limit): return self.versions.exclude(unreleased=True) \ .order_by('-order_idx')[:limit] def latest_version(self): versions = list(self.latest_versions(1)) if versions: return versions[0] def get_display_name(self): return u'{0}/{1}'.format( self.namespace, self.name) @staticmethod def create_uniq_name(namespace, name): """Returns a name which is unique in given namespace. Name is created by incrementing a value.""" if namespace and name: base_name = name counter = 0 while Changelog.objects.filter( namespace=namespace, name=name).exists(): counter += 1 name = '{0}{1}'.format(base_name, counter) return name @staticmethod def get_all_namespaces(like=None): queryset = Changelog.objects.all() if like is not None: queryset = queryset.filter( namespace__iexact=like ) return list(queryset.values_list('namespace', flat=True).distinct()) @staticmethod def normalize_namespaces(): namespaces_usage = defaultdict(int) changelogs_with_namespaces = Changelog.objects.exclude(namespace=None) for namespace in changelogs_with_namespaces.values_list('namespace', flat=True): namespaces_usage[namespace] += 1 def normalize(namespace): lowercased = namespace.lower() # here we process only capitalized namespaces if namespace == lowercased: return # if there lowercased is not used at all if lowercased not in namespaces_usage: return lowercased_count = namespaces_usage[lowercased] this_count = namespaces_usage[namespace] if lowercased_count >= this_count: # if num of occurences is equal, # prefer lowercased name Changelog.objects.filter( namespace=namespace).update( namespace=lowercased) else: Changelog.objects.filter( namespace=lowercased).update( namespace=namespace) del namespaces_usage[namespace] del namespaces_usage[lowercased] all_namespaces = namespaces_usage.keys() all_namespaces.sort() for namespace in all_namespaces: normalize(namespace) def save(self, *args, **kwargs): if self.id is None: # than objects just created and this is good # time to fix it's namespace existing_namespaces = Changelog.get_all_namespaces(like=self.namespace) if existing_namespaces: self.namespace = existing_namespaces[0] return super(Changelog, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('project', namespace=self.namespace, name=self.name) def editable_by(self, user, light_user=None): light_moderators = set(self.light_moderators.values_list('light_user', flat=True)) moderators = set(self.moderators.values_list('id', flat=True)) if user.is_authenticated(): # Any changelog could be edited by me if user.is_superuser: return True if moderators or light_moderators: return user.id in moderators else: if moderators or light_moderators: return light_user in light_moderators return True def is_unsuccessful(self): return self.name is None or \ self.namespace is None or \ self.downloader is None or \ not self.source def is_moderator(self, user, light_user=None): light_moderators = set(self.light_moderators.values_list('light_user', flat=True)) moderators = set(self.moderators.values_list('id', flat=True)) if user.is_authenticated(): return user.id in moderators else: return light_user in light_moderators def add_to_moderators(self, user, light_user=None): """Adds user to moderators and returns 'normal' or 'light' if it really added him. In case if user already was a moderator, returns None.""" if not self.is_moderator(user, light_user): if user.is_authenticated(): Moderator.objects.create(changelog=self, user=user) return 'normal' else: if light_user is not None: self.light_moderators.create(light_user=light_user) return 'light' def create_issue(self, type, comment='', related_versions=[]): joined_versions = u', '.join(related_versions) # for some types, only one issue at a time is allowed if type == 'lesser-version-count': if self.issues.filter(type=type, resolved_at=None, related_versions=joined_versions).count() > 0: return issue = self.issues.create(type=type, comment=comment.format(related_versions=joined_versions), related_versions=joined_versions) chat.send(u'New issue of type "{issue.type}" with comment: "{issue.comment}" was created for <https://allmychanges.com/issues/?namespace={issue.changelog.namespace}&name={issue.changelog.name}|{issue.changelog.namespace}/{issue.changelog.name}>'.format( issue=issue)) def resolve_issues(self, type): self.issues.filter(type=type, resolved_at=None).update(resolved_at=timezone.now()) def create_preview(self, user, light_user, **params): params.setdefault('downloader', self.downloader) params.setdefault('downloader_settings', self.downloader_settings) params.setdefault('downloaders', self.downloaders) params.setdefault('source', self.source) params.setdefault('search_list', self.search_list) params.setdefault('ignore_list', self.ignore_list) params.setdefault('xslt', self.xslt) preview = self.previews.create(user=user, light_user=light_user, **params) # preview_test_task.delay( # preview.id, # ['Guessing downloders', # 'Downloading using git', # 'Searching versions', # 'Nothing found', # 'Downloading from GitHub Review', # 'Searching versions', # 'Some results were found']) return preview def set_status(self, status, **kwargs): changed_fields = ['status', 'updated_at'] if status == 'error': self.problem = kwargs.get('problem') changed_fields.append('problem') self.status = status self.updated_at = timezone.now() self.save(update_fields=changed_fields) def set_processing_status(self, status, level=logging.INFO): self.processing_status = status[:PROCESSING_STATUS_LENGTH] self.updated_at = timezone.now() self.save(update_fields=('processing_status', 'updated_at')) key = 'preview-processing-status:{0}'.format(self.id) cache.set(key, status, 10 * 60) def get_processing_status(self): key = 'preview-processing-status:{0}'.format(self.id) result = cache.get(key, self.processing_status) return result def calc_next_update(self): """Returns date and time when next update should be scheduled. """ hour = 60 * 60 min_update_interval = hour max_update_interval = 48 * hour num_trackers = self.trackers.count() # here we divide max interval on 2 because # on the last stage will add some randomness to # the resulting value time_to_next_update = (max_update_interval / 2) / math.log(max(math.e, num_trackers)) time_to_next_update = max(min_update_interval, time_to_next_update, 2 * self.last_update_took) # add some randomness time_to_next_update = random.randint( int(time_to_next_update * 0.8), int(time_to_next_update * 2.0)) # limit upper bound return timezone.now() + datetime.timedelta(0, time_to_next_update) def calc_next_update_if_error(self): # TODO: check and remove return timezone.now() + datetime.timedelta(0, 1 * 60 * 60) def schedule_update(self, async=True, full=False): with log.fields(changelog_name=self.name, changelog_namespace=self.namespace, async=async, full=full): log.info('Scheduling changelog update') self.set_status('processing') self.set_processing_status('Waiting in the queue') self.problem = None self.save() if full: self.versions.all().delete() if async: update_changelog_task.delay(self.id) else: update_changelog_task(self.id) def resume(self): self.paused_at = None self.next_update_at = timezone.now() # we don't need to save here, because this will be done in schedule_update self.schedule_update() def clean(self): super(Changelog, self).clean() self.source, _, _ = normalize_url(self.source, for_checkout=False) def update_description_from_source(self, fall_asleep_on_rate_limit=False): # right now this works only for github urls if 'github.com' not in self.source: return url, username, repo = normalize_url(self.source) url = 'https://api.github.com/repos/{0}/{1}'.format(username, repo) headers={'Authorization': 'token ' + settings.GITHUB_TOKEN} response = requests.get(url, headers=headers) if response.status_code == 200: data = response.json() self.description = data.get('description', '') self.save(update_fields=('description', )) if fall_asleep_on_rate_limit: remaining = int(response.headers['x-ratelimit-remaining']) if remaining == 1: to_sleep = int(response.headers['x-ratelimit-reset']) - time.time() + 10 print 'OK, now I need to sleep {0} seconds because of GitHub\'s rate limit.'.format(to_sleep) time.sleep(to_sleep) def add_synonym(self, synonym): """Just a shortcut.""" if self.synonyms.filter(source=synonym).count() == 0: # if this synonym already bound to some another project # then raise exception found = list(SourceSynonym.objects.filter(source=synonym)) if found: with log.fields(changelog_id=self.pk, another_changelog_id=found[0].changelog_id): raise SynonymError('Synonym already bound to a changelog') found = list(Changelog.objects.filter(source=synonym)) if found: with log.fields(changelog_id=self.pk, another_changelog_id=found[0].pk): raise SynonymError('Synonym matches a changelog\'s source') self.synonyms.create(source=synonym) def merge_into(self, to_ch): # move trackers to_ch_trackers = set(to_ch.trackers.values_list('id', flat=True)) for user in self.trackers.all(): if user.id not in to_ch_trackers: ChangelogTrack.objects.create(user=user, changelog=to_ch) action = 'moved-during-merge' action_description = 'User was moved from {0}/{1} to changelog:{2}'.format( self.namespace, self.name, to_ch.id) UserHistoryLog.write(user, '', action, action_description) # move issues for issue in self.issues.all(): issue.changelog = to_ch issue.save(update_fields=('changelog',)) # remove itself Changelog.objects.filter(pk=self.pk).delete() # add synonym to_ch.add_synonym(self.source) def set_tag(self, user, name, version_number): """Sets or updates tag with `name` on the version. If tag was updated, returns 'updated' otherwise, returns 'created' """ assert isinstance(version_number, basestring), \ 'Parameter "version_number" should be a string, not "{0}"'.format( type(version_number)) params = dict(user=user, name=name) existing_tag = self.tags.filter( **params) update = existing_tag.count() > 0 if update: existing_tag.delete() version = get_one_or_none(self.versions, number=version_number) self.tags.create(version=version, version_number=version_number, **params) return 'updated' if update else 'created' def remove_tag(self, user, name): """Removes tag with `name` on the version. """ self.tags.filter(user=user, name=name).delete() class SourceSynonym(models.Model): changelog = models.ForeignKey(Changelog, related_name='synonyms') created_at = models.DateTimeField(default=timezone.now) source = URLField(unique=True) class ChangelogTrack(models.Model): user = models.ForeignKey(User) changelog = models.ForeignKey(Changelog) created_at = models.DateTimeField(default=timezone.now) class ChangelogSkip(models.Model): user = models.ForeignKey(User) changelog = models.ForeignKey(Changelog) created_at = models.DateTimeField(default=timezone.now) class Issue(models.Model): """Keeps track any issues, related to a changelog. """ changelog = models.ForeignKey(Changelog, related_name='issues', blank=True, null=True) user = models.ForeignKey(User, related_name='issues', blank=True, null=True) light_user = models.CharField(max_length=40, blank=True, null=True) type = models.CharField(max_length=40) comment = models.TextField() created_at = models.DateTimeField(auto_now_add=True) resolved_at = models.DateTimeField(blank=True, null=True) resolved_by = models.ForeignKey(User, related_name='resolved_issues', blank=True, null=True) related_versions = models.TextField(default='', blank=True, help_text='Comma-separated list of versions, related to this issue') email = models.CharField(max_length=100, blank=True, null=True) page = models.CharField(max_length=100, blank=True, null=True) importance = models.IntegerField(db_index=True, blank=True, default=0) __repr__ = make_repr('changelog', 'type', 'comment', 'created_at', 'resolved_at') def save(self, *args, **kwargs): if not self.importance: self.importance = calculate_issue_importance( num_trackers=self.changelog.trackers.count() if self.changelog else 0, user=self.user, light_user=self.light_user) return super(Issue, self).save(*args, **kwargs) @staticmethod def merge(user, light_user): entries = Issue.objects.filter(user=None, light_user=light_user) if entries.count() > 0: with log.fields(username=user.username, num_entries=entries.count(), light_user=light_user): log.info('Merging issues') entries.update(user=user) def editable_by(self, user, light_user=None): return self.changelog.editable_by(user, light_user) def get_related_versions(self): response = [version.strip() for version in self.related_versions.split(',')] return filter(None, response) def get_related_deployments(self): return DeploymentHistory.objects \ .filter(deployed_at__lte=self.created_at) \ .order_by('-id')[:3] def resolve(self, user, notify=True): self.resolved_at = timezone.now() self.resolved_by = user self.save(update_fields=('resolved_at', 'resolved_by')) if notify: chat.send((u'Issue <https://allmychanges.com{url}|#{issue_id}> ' u'for {namespace}/{name} was resolved by {username}.').format( url=reverse('issue-detail', pk=self.id), issue_id=self.id, namespace=self.changelog.namespace, name=self.changelog.name, username=user.username)) if self.type == 'auto-paused': changelog = self.changelog with log.fields(changelog_id=changelog.id): log.info('Resuming changelog updates') changelog.resume() if notify: chat.send(u'Autopaused package {namespace}/{name} was resumed {username}.'.format( namespace=changelog.namespace, name=changelog.name, username=user.username)) class IssueComment(models.Model): issue = models.ForeignKey(Issue, related_name='comments') user = models.ForeignKey(User, blank=True, null=True, related_name='issue_comments') created_at = models.DateTimeField(default=timezone.now) message = models.TextField() class DiscoveryHistory(models.Model): """Keeps track any issues, related to a changelog. """ changelog = models.ForeignKey(Changelog, related_name='discovery_history') discovered_versions = models.TextField() new_versions = models.TextField() num_discovered_versions = models.IntegerField() num_new_versions = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) __repr__ = make_repr('discovered_versions') class LightModerator(models.Model): """These entries are created when anonymouse user adds another package into the system. When user signs up, these entries should be transformed into the Moderator entries. """ changelog = models.ForeignKey(Changelog, related_name='light_moderators') light_user = models.CharField(max_length=40) created_at = models.DateTimeField(auto_now_add=True) @staticmethod def merge(user, light_user): entries = LightModerator.objects.filter(light_user=light_user) for entry in entries: with log.fields(username=user.username, light_user=light_user): log.info('Transforming light moderator into the permanent') Moderator.objects.create( changelog=entry.changelog, user=user, from_light_user=light_user) entries.delete() @staticmethod def remove_stale_moderators(): LightModerator.objects.filter( created_at__lte=timezone.now() - datetime.timedelta(1)).delete() class Moderator(models.Model): changelog = models.ForeignKey(Changelog, related_name='+') user = models.ForeignKey(User, related_name='+') created_at = models.DateTimeField(auto_now_add=True) from_light_user = models.CharField(max_length=40, blank=True, null=True) class Preview(Downloadable, models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='previews', blank=True, null=True) changelog = models.ForeignKey(Changelog, related_name='previews') light_user = models.CharField(max_length=40) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(blank=True, null=True) source = models.URLField() ignore_list = models.CharField(max_length=1000, default='', help_text=('Comma-separated list of directories' ' and filenames to ignore searching' ' changelog.'), blank=True) # TODO: remove this field after migration on production check_list = models.CharField(max_length=1000, default='', help_text=('Comma-separated list of directories' ' and filenames to search' ' changelog.'), blank=True) search_list = models.CharField(max_length=1000, default='', help_text=('Comma-separated list of directories' ' and filenames to search' ' changelog.'), blank=True) xslt = models.TextField(default='', help_text=('XSLT transform to be applied to all html files.'), blank=True) problem = models.CharField(max_length=1000, help_text='Latest error message', blank=True, null=True) downloader = models.CharField(max_length=255, blank=True, null=True) downloader_settings = jsonfield.JSONField( default={}, help_text=('JSON with settings for selected downloader.'), blank=True) downloaders = jsonfield.JSONField( default=[], help_text=('JSON with guessed downloaders and their additional meta information.'), blank=True) done = models.BooleanField(default=False) status = models.CharField(max_length=40, default='created') processing_status = models.CharField(max_length=40) log = jsonfield.JSONField(default=[], help_text=('JSON with log of all operation applied during preview processing.'), blank=True) @property def namespace(self): return self.changelog.namespace @property def name(self): return self.changelog.name @property def description(self): return self.changelog.description def set_status(self, status, **kwargs): changed_fields = ['status', 'updated_at'] if status == 'processing': self.versions.all().delete() self.updated_at = timezone.now() changed_fields.append('updated_at') elif status == 'error': self.problem = kwargs.get('problem') changed_fields.append('problem') self.status = status self.updated_at = timezone.now() self.save(update_fields=changed_fields) def set_processing_status(self, status, level=logging.INFO): self.log.append(status) self.processing_status = status[:PROCESSING_STATUS_LENGTH] self.updated_at = timezone.now() self.save(update_fields=('processing_status', 'updated_at', 'log')) key = 'preview-processing-status:{0}'.format(self.id) cache.set(key, status, 10 * 60) def get_processing_status(self): key = 'preview-processing-status:{0}'.format(self.id) result = cache.get(key, self.processing_status) return result def schedule_update(self): self.set_status('processing') self.set_processing_status('Waiting in the queue') self.versions.all().delete() update_preview_task.delay(self.pk) class VersionManager(models.Manager): use_for_related_fields = True def create(self, *args, **kwargs): version = super(VersionManager, self).create(*args, **kwargs) changelog = kwargs.get('changelog') if changelog: version.associate_with_free_tags() return version def released(self): return self.exclude(unreleased=True) def unreleased(self): return self.filter(unreleased=True) class Version(models.Model): changelog = models.ForeignKey(Changelog, related_name='versions', blank=True, null=True, on_delete=models.SET_NULL) preview = models.ForeignKey(Preview, related_name='versions', blank=True, null=True, on_delete=models.SET_NULL) date = models.DateField(blank=True, null=True) number = models.CharField(max_length=255) unreleased = models.BooleanField(default=False) discovered_at = models.DateTimeField(blank=True, null=True) last_seen_at = models.DateTimeField(blank=True, null=True) filename = models.CharField(max_length=1000, help_text=('Source file where this version was found'), blank=True, null=True) raw_text = models.TextField(blank=True, null=True) processed_text = models.TextField(blank=True, null=True) order_idx = models.IntegerField(blank=True, null=True, help_text=('This field is used to reorder versions ' 'according their version numbers and to ' 'fetch them from database efficiently.')) tweet_id = models.CharField(max_length=1000, help_text=('Tweet id or None if we did not tweeted about this version yet.'), blank=True, null=True) objects = VersionManager() class Meta: get_latest_by = 'order_idx' ordering = ['-order_idx'] def __unicode__(self): return self.number def get_absolute_url(self): return self.changelog.get_absolute_url() + '#' + self.number def post_tweet(self): if not settings.TWITTER_CREDS: return if self.unreleased: raise RuntimeError('Unable to tweet about unreleased version') if self.tweet_id: return # because we already posted a tweet ch = self.changelog image_url = settings.BASE_URL + ch.get_absolute_url() \ + '?snap=1&version=' + self.number filename = sha1(image_url).hexdigest() + '.png' full_path = os.path.join(settings.SNAPSHOTS_ROOT, filename) result = envoy.run( '{root}/makescreenshot --width 590 --height 600 {url} {path}'.format( root=settings.PROJECT_ROOT, url=image_url, path=full_path)) if result.status_code != 0: with log.fields( status_code=result.status_code, std_out=result.std_out, std_err=result.std_err): log.error('Unable to make a screenshot') raise RuntimeError('Unable to make a screenshot') with open(full_path, 'rb') as f: from requests_oauthlib import OAuth1 auth = OAuth1(*settings.TWITTER_CREDS) response = requests.post( 'https://upload.twitter.com/1.1/media/upload.json', auth=auth, files={'media': ('screenshot.png', f.read(), 'image/png')}) media_id = response.json()['media_id_string'] url = settings.BASE_URL + self.get_absolute_url() text = '{number} of {namespace}/{name} was released: {url} #{namespace} #{name} #release'.format( number=self.number, namespace=ch.namespace, name=ch.name, url=url) response = requests.post( 'https://api.twitter.com/1.1/statuses/update.json', auth=auth, data={'status': text, 'media_ids': media_id}) if response.status_code == 200: self.tweet_id = response.json()['id_str'] self.save(update_fields=('tweet_id',)) return full_path def set_tag(self, user, name): """Convenience method to set tag on just this version. """ self.changelog.set_tag(user, name, self.number) def associate_with_free_tags(self): # associate free tags with this version for tag in self.changelog.tags.filter(version_number=self.number): tag.version = self tag.save(update_fields=('version',)) class Tag(models.Model): # this field shouldn't be blank or null # but I have to make it so, because otherwise # DB migrations wasn't possible changelog = models.ForeignKey(Changelog, blank=True, null=True, related_name='tags') # tag may be tied to a version in the database, # but in some cases, we may don't have parsed version # with given number version = models.ForeignKey(Version, blank=True, null=True, related_name='tags') user = models.ForeignKey(User, related_name='tags') # regex=ur'[a-z][a-z0-9-]*[a-z0-9]' name = models.CharField(max_length=40) # we have not any restrictions on the format of this field # this could be any string even something like 'latest' version_number = models.CharField(max_length=40) created_at = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ('changelog', 'user', 'name') def get_absolute_url(self): # the name shouldn't contain any unicode or nonascii letters nor spaces # otherwise, we need to encode tu utf-8 and quote_plus it. return self.changelog.get_absolute_url() + '#' + self.name __repr__ = make_repr('name', 'version_number') class FeedItem(models.Model): user = models.ForeignKey(User) version = models.ForeignKey(Version, related_name='feed_items') created_at = models.DateTimeField(auto_now_add=True) ACTIVE_USER_ACTIONS = ( u'landing-digest-view', u'landing-track', u'landing-ignore', u'login', u'profile-update', u'digest-view', u'package-view', u'package-create', u'package-edit', u'edit-digest-view', u'index-view', u'track', u'untrack', u'untrack-allmychanges', u'create-issue', u'email-digest-open', u'email-digest-click') class UserHistoryLog(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='history_log', blank=True, null=True) light_user = models.CharField(max_length=40) action = models.CharField(max_length=40) description = models.CharField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) @staticmethod def merge(user, light_user): entries = UserHistoryLog.objects.filter(user=None, light_user=light_user) if entries.count() > 0: with log.fields(username=user.username, num_entries=entries.count(), light_user=light_user): log.info('Merging user history logs') entries.update(user=user) @staticmethod def write(user, light_user, action, description): user = user if user is not None and user.is_authenticated() else None return UserHistoryLog.objects.create(user=user, light_user=light_user, action=action, description=description) class UserStateHistory(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='state_history') date = models.DateField() state = models.CharField(max_length=40) class DeploymentHistory(models.Model): hash = models.CharField(max_length=32, default='') description = models.TextField() deployed_at = models.DateTimeField(auto_now_add=True) __repr__ = make_repr('deployed_at', 'hash') class EmailVerificationCode(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='email_verification_code') hash = models.CharField(max_length=32, default='') deployed_at = models.DateTimeField(auto_now_add=True) @staticmethod def new_code_for(user): hash = md5(str(time.time()) + settings.SECRET_KEY).hexdigest() try: code = user.email_verification_code code.hash = hash code.save() except EmailVerificationCode.DoesNotExist: code = EmailVerificationCode.objects.create( user=user, hash=hash) return code AUTOCOMPLETE_TYPES = ( ('source', 'Source URL'), ('namespace', 'Namespace'), ('package', 'Package')) AUTOCOMPLETE_ORIGINS = ( ('app-store', 'App Store'), ('pypi', 'PyPi')) COMMON_WORDS = set('a,able,about,across,after,all,almost,also,am,among,an,and,any,are,as,at,be,because,been,but,by,can,cannot,could,dear,did,do,does,either,else,ever,every,for,from,get,got,had,has,have,he,her,hers,him,his,how,however,i,if,in,into,is,it,its,just,least,let,like,likely,may,me,might,most,must,my,neither,no,nor,not,of,off,often,on,only,or,other,our,own,rather,said,say,says,she,should,since,so,some,than,that,the,their,them,then,there,these,they,this,tis,to,too,twas,us,wants,was,we,were,what,when,where,which,while,who,whom,why,will,with,would,yet,you,your'.split(',')) class AutocompleteData(models.Model): origin = models.CharField(max_length=100, choices=AUTOCOMPLETE_ORIGINS) title = models.CharField(max_length=255) description = models.CharField(max_length=DESCRIPTION_LENGTH, default='') type = models.CharField(max_length=10, choices=AUTOCOMPLETE_TYPES) source = models.CharField(max_length=255, # we need this because MySQL will output warning and break our migrations for greater length blank=True, null=True, db_index=True) icon = models.CharField(max_length=255, blank=True, null=True) changelog = models.ForeignKey(Changelog, blank=True, null=True, related_name='autocomplete') score = models.IntegerField(default=0, help_text=('A value from 0 to infinity. ' 'Items with bigger values ' 'should appear at the top ' 'of the suggest.')) __repr__ = make_repr('title') def save(self, *args, **kwargs): super(AutocompleteData, self).save(*args, **kwargs) if self.words.count() == 0: self.add_words() def add_words(self, db_name='default'): if db_name == 'default': data = self else: data = AutocompleteData.objects.using(db_name).get(pk=self.pk) words = data.title.split() words = (word.strip() for word in words) words = set(word.lower() for word in words if len(word) > 3) words -= COMMON_WORDS words.add(data.title.lower()) words = [AutocompleteWord2.objects.using(db_name).get_or_create(word=word)[0] for word in words] data.words2.add(*words) class AutocompleteWord(models.Model): word = models.CharField(max_length=100, db_index=True) data = models.ForeignKey(AutocompleteData, related_name='words') __repr__ = make_repr('word') class AutocompleteWord2(models.Model): word = models.CharField(max_length=100, unique=True) data_objects = models.ManyToManyField( AutocompleteData, related_name='words2') __repr__ = make_repr('word') class AppStoreBatch(models.Model): """To identify separate processing batches. """ created = models.DateTimeField(auto_now_add=True) __repr__ = make_repr() class AppStoreUrl(models.Model): """This model is used when we are fetching data from app store for our autocomplete. Use management command update_appstore_urls to populate this collection. """ # we need this because MySQL will output warning and break our migrations for greater length source = models.CharField(max_length=255, blank=True, null=True, unique=True) autocomplete_data = models.OneToOneField(AutocompleteData, blank=True, null=True, related_name='appstore_url', on_delete=models.SET_NULL) batch = models.ForeignKey(AppStoreBatch, blank=True, null=True, related_name='urls', on_delete=models.SET_NULL) rating = models.FloatField(blank=True, null=True) rating_count = models.IntegerField(blank=True, null=True) __repr__ = make_repr('source') class MandrillMessage(models.Model): mid = models.CharField(max_length=32, help_text='Mandrills ID', db_index=True) timestamp = models.IntegerField() email = models.EmailField() user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='mandrill_messages', on_delete=models.SET_NULL, blank=True, null=True) payload = models.TextField() __repr__ = make_repr('mid', 'email')
AllMyChanges/allmychanges.com
allmychanges/models.py
Python
bsd-2-clause
55,463
'use strict' class ScheduleEvents { constructor (aws) { // Authenticated `aws` object in `lib/main.js` this.lambda = new aws.Lambda({ apiVersion: '2015-03-31' }) this.cloudwatchevents = new aws.CloudWatchEvents({ apiVersion: '2015-10-07' }) } _ruleDescription (params) { if ('ScheduleDescription' in params && params.ScheduleDescription != null) { return `${params.ScheduleDescription}` } return `${params.ScheduleName} - ${params.ScheduleExpression}` } _functionName (params) { return params.FunctionArn.split(':').pop() } _putRulePrams (params) { return { Name: params.ScheduleName, Description: this._ruleDescription(params), State: params.ScheduleState, ScheduleExpression: params.ScheduleExpression } } _putRule (params) { // return RuleArn if created return new Promise((resolve, reject) => { const _params = this._putRulePrams(params) this.cloudwatchevents.putRule(_params, (err, rule) => { if (err) reject(err) resolve(rule) }) }) } _addPermissionParams (params) { return { Action: 'lambda:InvokeFunction', FunctionName: this._functionName(params), Principal: 'events.amazonaws.com', SourceArn: params.RuleArn, StatementId: params.ScheduleName } } _addPermission (params) { return new Promise((resolve, reject) => { const _params = this._addPermissionParams(params) this.lambda.addPermission(_params, (err, data) => { if (err) { if (err.code !== 'ResourceConflictException') reject(err) // If it exists it will result in an error but there is no problem. resolve('Permission already set') } resolve(data) }) }) } _putTargetsParams (params) { return { Rule: params.ScheduleName, Targets: [{ Arn: params.FunctionArn, Id: this._functionName(params), Input: params.hasOwnProperty('Input') ? JSON.stringify(params.Input) : '' }] } } _putTargets (params) { return new Promise((resolve, reject) => { const _params = this._putTargetsParams(params) this.cloudwatchevents.putTargets(_params, (err, data) => { // even if it is already registered, it will not be an error. if (err) reject(err) resolve(data) }) }) } add (params) { return Promise.resolve().then(() => { return this._putRule(params) }).then(rule => { return this._addPermission(Object.assign(params, rule)) }).then(data => { return this._putTargets(params) }) } } module.exports = ScheduleEvents
teebu/node-lambda
lib/schedule_events.js
JavaScript
bsd-2-clause
2,692
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using ITCC.Logging.Core; namespace ITCC.Logging.Reader.Core.Utils { public class EntryTokenizer { #region public /// <summary> /// We parse line that: /// 1) Starts with [ /// 2) DOES NOT contain '\n' at the end /// </summary> /// <param name="segment">Line bytes</param> /// <returns>Parsed entry or null in case of error</returns> public static LogEntryEventArgs ParseEntry(byte[] segment) { var tokenizer = new EntryTokenizer(segment); return tokenizer.ParseEntry(); } #endregion #region private private EntryTokenizer(byte[] segment) { _segment = Encoding.UTF8.GetChars(segment); LogMessage(LogLevel.Info, $"Parsing string of length {_segment.Length}: {ToLiteral(Encoding.UTF8.GetString(segment))}"); _position = 1; } private LogEntryEventArgs ParseEntry() { if (!CheckNextSegmentExists()) return null; var dateString = ParseNextSegment(); DateTime date; LogMessage(LogLevel.Trace, $"Date string: {dateString}"); if (!DateTime.TryParseExact(dateString, "dd.MM.yyyy HH:mm:ss.fff", new DateTimeFormatInfo(), DateTimeStyles.AllowInnerWhite, out date)) { return null; } if (!CheckNextSegmentExists()) return null; var levelString = ParseNextSegment(); var level = ParseLogLevel(levelString); LogMessage(LogLevel.Trace, $"Loglevel string: {levelString}"); if (level == LogLevel.None) { return null; } if (!CheckNextSegmentExists()) return null; Skip(ThreadMark); var threadString = ParseNextSegment(); LogMessage(LogLevel.Trace, $"Thread string: {threadString}"); int threadId; if (!int.TryParse(threadString, out threadId)) { return null; } if (!CheckNextSegmentExists()) return null; var scope = ParseNextSegment(false); LogMessage(LogLevel.Trace, $"Scope string: {scope}"); var message = ReadToEnd(); LogMessage(LogLevel.Trace, $"Message string: {message}"); return LogEntryEventArgs.CreateFromRawData(date, level, threadId, scope, message); } private string ParseNextSegment(bool leftAligned = true) { var newPosition = _position; int actualStart; int actualEnd; if (leftAligned) { actualStart = newPosition; var possibleEnd = -1; var wasWhiteSpace = false; while (_segment[newPosition] != PartEnd) { if (_segment[newPosition] == WhiteSpace) { if (!wasWhiteSpace) possibleEnd = newPosition - 1; wasWhiteSpace = true; } else { possibleEnd = newPosition; wasWhiteSpace = false; } newPosition++; } actualEnd = wasWhiteSpace ? possibleEnd : newPosition - 1; } else { while (_segment[newPosition] == WhiteSpace) { newPosition++; } actualStart = newPosition; while (_segment[newPosition] != PartEnd) { newPosition++; } actualEnd = newPosition - 1; } // Skip "] [" and go to next segment _position = newPosition + 3; LogMessage(LogLevel.Trace, $"Start: {actualStart}. End: {actualEnd}"); var actualLength = actualEnd - actualStart + 1; var buffer = new char[actualLength]; Array.Copy(_segment, actualStart, buffer, 0, actualLength); return new string(buffer); } private bool CheckNextSegmentExists() { var exists = _segment[_position - 1] == PartStart; if (! exists) LogMessage(LogLevel.Trace, "Next segment does not exist"); return exists; } private string ReadToEnd() { // Now we have no [ _position--; var builder = new StringBuilder(); builder.Append(_segment, _position, _segment.Length - _position); return builder.ToString(); } private void Skip(string mark) { var bytes = mark.ToCharArray(); var i = 0; while (i < bytes.Length && _segment[_position + i] == bytes[i]) { i++; } _position += i; } private static string ToLiteral(string input) { using (var writer = new StringWriter()) { using (var provider = CodeDomProvider.CreateProvider("CSharp")) { provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null); return writer.ToString(); } } } private static LogLevel ParseLogLevel(string representation) { switch (representation) { case "TRACE": return LogLevel.Trace; case "DEBUG": return LogLevel.Debug; case "INFO": return LogLevel.Info; case "WARN": return LogLevel.Warning; case "ERROR": return LogLevel.Error; case "CRIT": return LogLevel.Critical; default: return LogLevel.None; } } [Conditional("DEBUG")] private void LogMessage(LogLevel level, string message) => Logger.LogEntry("TOKENIZER", level, message); private const string ThreadMark = @"THR "; private const char PartStart = '['; private const char PartEnd = ']'; private const char WhiteSpace = ' '; private int _position; private readonly char[] _segment; #endregion } }
OPEXGroup/ITCC.Library
src/ITCC.Logging.Reader.Core/Utils/EntryTokenizer.cs
C#
bsd-2-clause
6,972
package org.oors; import java.util.Date; import javax.persistence.TypedQuery; import javax.swing.text.html.HTMLDocument; public abstract class Base extends OorsEventGenerator { private static final String NULL_ATTRIBUTE = "Null attribute parameter"; private static final String INVALID_VALUE_TYPE = "Attribute value type incorrect"; private static final String INVALID_FOR_TYPE = "Attribute for type incorrect"; private static final String NULL_VALUE = "Null value passed"; abstract long getId(); abstract ProjectBranch getProjectBranch(); public boolean getBooleanValue( Attribute attribute ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.BOOLEAN ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeBooleanValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeBooleanValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeBooleanValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { return q.getSingleResult().getValue(); } catch ( Exception ex ) { AttributeBooleanValue asv = new AttributeBooleanValue(attribute,this.getId(),false); DataSource.getInstance().persist(asv); return asv.getValue(); } } public void setBooleanValue( Attribute attribute, boolean value ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.BOOLEAN ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeBooleanValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeBooleanValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeBooleanValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { q.getSingleResult().setValue(value); } catch ( Exception ex ) { AttributeBooleanValue asv = new AttributeBooleanValue(attribute,this.getId(),value); DataSource.getInstance().persist(asv); asv.setValue(value); } } public Date getDateValue( Attribute attribute ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.DATE ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeDateValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeDateValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeDateValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { return q.getSingleResult().getValue(); } catch ( Exception ex ) { AttributeDateValue asv = new AttributeDateValue(attribute,this.getId(),new Date()); DataSource.getInstance().persist(asv); return asv.getValue(); } } public void setDateValue( Attribute attribute, Date value ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.DATE ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeDateValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeDateValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeDateValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { q.getSingleResult().setValue(value); } catch ( Exception ex ) { AttributeDateValue asv = new AttributeDateValue(attribute,this.getId(),value); DataSource.getInstance().persist(asv); asv.setValue(value); } } public String getStringValue( Attribute attribute ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.STRING ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeStringValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeStringValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeStringValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { return q.getSingleResult().getValue(); } catch ( Exception ex ) { AttributeStringValue asv = new AttributeStringValue(attribute,this.getId(),"Default"); DataSource.getInstance().persist(asv); return asv.getValue(); } } public void setStringValue( Attribute attribute, String value ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.STRING ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); if ( value==null ) throw new AttributeException(NULL_VALUE); TypedQuery<AttributeStringValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeStringValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeStringValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { q.getSingleResult().setValue(value); } catch ( Exception ex ) { AttributeStringValue asv = new AttributeStringValue(attribute,this.getId(),value); DataSource.getInstance().persist(asv); asv.setValue(value); } } public javax.swing.text.html.HTMLDocument getHTMLValue( Attribute attribute ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.HTML ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeHTMLValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeHTMLValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeHTMLValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { return q.getSingleResult().getValue(); } catch ( Exception ex ) { AttributeHTMLValue asv = new AttributeHTMLValue(attribute,this.getId(),new javax.swing.text.html.HTMLDocument()); DataSource.getInstance().persist(asv); return asv.getValue(); } } public void setHTMLValue( Attribute attribute, javax.swing.text.html.HTMLDocument value ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.HTML ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeHTMLValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeHTMLValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeHTMLValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { q.getSingleResult().setValue(value); } catch ( Exception ex ) { AttributeHTMLValue asv = new AttributeHTMLValue(attribute,this.getId(),value); DataSource.getInstance().persist(asv); asv.setValue(value); } } public double getNumberValue( Attribute attribute ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.NUMBER ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeNumberValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeNumberValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeNumberValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { return q.getSingleResult().getValue(); } catch ( Exception ex ) { AttributeNumberValue asv = new AttributeNumberValue(attribute,this.getId(),0.0); DataSource.getInstance().persist(asv); return asv.getValue(); } } public void setNumberValue( Attribute attribute, double value ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.NUMBER ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeNumberValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeNumberValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeNumberValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { q.getSingleResult().setValue(value); } catch ( Exception ex ) { AttributeNumberValue asv = new AttributeNumberValue(attribute,this.getId(),value); DataSource.getInstance().persist(asv); asv.setValue(value); } } public Object getValue( Attribute attribute ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE+", Expected: " +attribute.getForType()+", Found: "+this.getClass()); switch ( attribute.valueType ) { case BOOLEAN: return this.getBooleanValue(attribute); case DATE: return this.getDateValue(attribute); case HTML: return this.getHTMLValue(attribute); case NUMBER: return this.getNumberValue(attribute); case STRING: return this.getStringValue(attribute); //case USER: return this.getUserValue(attribute); //case USERGROUP: return this.getUserGroupValue(attribute); default: return null; } } public void setValue(Attribute attribute, Object value) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); try { switch ( attribute.valueType ) { case BOOLEAN: this.setBooleanValue(attribute,(Boolean)value); case DATE: this.setDateValue(attribute,(Date)value); case HTML: this.setHTMLValue(attribute,(HTMLDocument)value); case NUMBER: this.setNumberValue(attribute,(Double)value); case STRING: this.setStringValue(attribute,(String)value); //case USER: this.getUserValue(attribute,value); //case USERGROUP: this.getUserGroupValue(attribute,value); } } catch ( ClassCastException ccex ) { throw new AttributeException(ccex.getMessage()); } } }
belteshazzar/oors
oors/src/org/oors/Base.java
Java
bsd-2-clause
12,619
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction from .aws import BaseARN service_name = "AWS Shield" prefix = "shield" class Action(BaseAction): def __init__(self, action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str = "", region: str = "", account: str = "") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account ) AssociateDRTLogBucket = Action("AssociateDRTLogBucket") AssociateDRTRole = Action("AssociateDRTRole") AssociateHealthCheck = Action("AssociateHealthCheck") AssociateProactiveEngagementDetails = Action("AssociateProactiveEngagementDetails") CreateProtection = Action("CreateProtection") CreateProtectionGroup = Action("CreateProtectionGroup") CreateSubscription = Action("CreateSubscription") DeleteProtection = Action("DeleteProtection") DeleteProtectionGroup = Action("DeleteProtectionGroup") DeleteSubscription = Action("DeleteSubscription") DescribeAttack = Action("DescribeAttack") DescribeAttackStatistics = Action("DescribeAttackStatistics") DescribeDRTAccess = Action("DescribeDRTAccess") DescribeEmergencyContactSettings = Action("DescribeEmergencyContactSettings") DescribeProtection = Action("DescribeProtection") DescribeProtectionGroup = Action("DescribeProtectionGroup") DescribeSubscription = Action("DescribeSubscription") DisableApplicationLayerAutomaticResponse = Action( "DisableApplicationLayerAutomaticResponse" ) DisableProactiveEngagement = Action("DisableProactiveEngagement") DisassociateDRTLogBucket = Action("DisassociateDRTLogBucket") DisassociateDRTRole = Action("DisassociateDRTRole") DisassociateHealthCheck = Action("DisassociateHealthCheck") EnableApplicationLayerAutomaticResponse = Action( "EnableApplicationLayerAutomaticResponse" ) EnableProactiveEngagement = Action("EnableProactiveEngagement") GetSubscriptionState = Action("GetSubscriptionState") ListAttacks = Action("ListAttacks") ListProtectionGroups = Action("ListProtectionGroups") ListProtections = Action("ListProtections") ListResourcesInProtectionGroup = Action("ListResourcesInProtectionGroup") ListTagsForResource = Action("ListTagsForResource") TagResource = Action("TagResource") UntagResource = Action("UntagResource") UpdateApplicationLayerAutomaticResponse = Action( "UpdateApplicationLayerAutomaticResponse" ) UpdateEmergencyContactSettings = Action("UpdateEmergencyContactSettings") UpdateProtectionGroup = Action("UpdateProtectionGroup") UpdateSubscription = Action("UpdateSubscription")
cloudtools/awacs
awacs/shield.py
Python
bsd-2-clause
2,682
package cn.xz.study.design.pattern.singleton; public class LazySingleton { /** * volatile 确保线程改变了变量的值时 会立刻同步改变量的值 以保证改变量的值是最新的 */ private volatile static LazySingleton singleton = null; private LazySingleton(){ } public static LazySingleton getInstance(){ if(singleton == null){ synchronized (LazySingleton.class){ singleton = new LazySingleton(); } } return singleton; } private int count = 0; public synchronized int add(){ return count++; } public int getCount() { return count; } }
xyz327/studyResource
study-design-pattern/src/main/java/cn/xz/study/design/pattern/singleton/LazySingleton.java
Java
bsd-2-clause
601
/* * Copyright (c) 2010, Joshua Lackey * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * 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. * * 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 HOLDER 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. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <pthread.h> #include <math.h> #include <complex> #include "bladeRF_source.h" extern int g_verbosity; bladeRF_source::bladeRF_source(float sample_rate, long int fpga_master_clock_freq) { m_fpga_master_clock_freq = fpga_master_clock_freq; m_desired_sample_rate = sample_rate; m_sample_rate = 0.0; m_decimation = 0; m_cb = new circular_buffer(CB_LEN, sizeof(complex), 0); pthread_mutex_init(&m_u_mutex, 0); } bladeRF_source::bladeRF_source(unsigned int decimation, long int fpga_master_clock_freq) { m_fpga_master_clock_freq = fpga_master_clock_freq; m_sample_rate = 0.0; m_cb = new circular_buffer(CB_LEN, sizeof(complex), 0); pthread_mutex_init(&m_u_mutex, 0); m_decimation = decimation & ~1; if(m_decimation < 4) m_decimation = 4; if(m_decimation > 256) m_decimation = 256; } bladeRF_source::~bladeRF_source() { stop(); delete m_cb; pthread_mutex_destroy(&m_u_mutex); } void bladeRF_source::stop() { pthread_mutex_lock(&m_u_mutex); #if 0 if(m_db_rx) m_db_rx->set_enable(0); if(m_u_rx) m_u_rx->stop(); #endif pthread_mutex_unlock(&m_u_mutex); } void bladeRF_source::start() { pthread_mutex_lock(&m_u_mutex); if (bladerf_enable_module(bdev, BLADERF_MODULE_RX, 1)) { } pthread_mutex_unlock(&m_u_mutex); } void bladeRF_source::calculate_decimation() { float decimation_f; #if 0 decimation_f = (float)m_u_rx->fpga_master_clock_freq() / m_desired_sample_rate; m_decimation = (unsigned int)round(decimation_f) & ~1; if(m_decimation < 4) m_decimation = 4; if(m_decimation > 256) m_decimation = 256; #endif } float bladeRF_source::sample_rate() { return m_sample_rate; } int bladeRF_source::tune_dac(int dac) { printf("DAC: 0x%.4x\n", dac); return bladerf_dac_write(bdev, dac); } int bladeRF_source::save_dac(int dac) { int rv; bool ok; bladerf_fpga_size fpga_size; struct bladerf_image *image = NULL; uint32_t page, count; bladerf_get_fpga_size(bdev, &fpga_size); image = bladerf_alloc_cal_image(bdev, fpga_size, dac); if (!image) { return 1; } rv = bladerf_erase_flash_bytes(bdev, BLADERF_FLASH_ADDR_CAL, BLADERF_FLASH_BYTE_LEN_CAL); if (rv != 0) { return 1; } rv = bladerf_write_flash_bytes(bdev, image->data, image->address, image->length); return 0; } int bladeRF_source::tune(double freq) { int r; pthread_mutex_lock(&m_u_mutex); r = bladerf_set_frequency(bdev, BLADERF_MODULE_RX, freq); pthread_mutex_unlock(&m_u_mutex); return !r; } bool bladeRF_source::set_antenna(int antenna) { return true; //return m_db_rx->select_rx_antenna(antenna); } bool bladeRF_source::set_gain(float gain) { float min = 0.5, max = 2.0; if((gain < 0.0) || (1.0 < gain)) return false; return !bladerf_set_rxvga2(bdev, 3); return !bladerf_set_rxvga2(bdev, min + gain * (max - min)); } /* * open() should be called before multiple threads access bladeRF_source. */ int bladeRF_source::open(unsigned int subdev) { int do_set_decim = 0; if(!bdev) { int status; if (bladerf_open(&bdev, NULL)) { printf("Couldn't open bladeRF\n"); exit(1); } #define DEFAULT_STREAM_XFERS 64 #define DEFAULT_STREAM_BUFFERS 5600 #define DEFAULT_STREAM_SAMPLES 2048 #define DEFAULT_STREAM_TIMEOUT 4000 status = bladerf_sync_config(bdev, static_cast<bladerf_channel_layout>(BLADERF_CHANNEL_RX(0)), BLADERF_FORMAT_SC16_Q11, DEFAULT_STREAM_BUFFERS, DEFAULT_STREAM_SAMPLES, DEFAULT_STREAM_XFERS, DEFAULT_STREAM_TIMEOUT ); if(!m_decimation) { do_set_decim = 1; m_decimation = 4; } // if(do_set_decim) { // calculate_decimation(); // } //m_u_rx->set_decim_rate(m_decimation); // m_sample_rate = (double)m_u_rx->fpga_master_clock_freq() / m_decimation; unsigned int bw; bladerf_set_bandwidth(bdev, BLADERF_MODULE_RX, 1500000u, &bw); printf("Actual filter bandwidth = %d kHz\n", bw/1000); int gain; bladerf_set_rxvga1(bdev, 20); bladerf_get_rxvga1(bdev, &gain); printf("rxvga1 = %d dB\n", gain); bladerf_set_rxvga2(bdev, 30); bladerf_set_lna_gain(bdev, BLADERF_LNA_GAIN_MAX); bladerf_get_rxvga2(bdev, &gain); bladerf_dac_write(bdev, 0xa1ea); printf("rxvga2 = %d dB\n", gain); struct bladerf_rational_rate rate, actual; rate.integer = (4 * 13e6) / 48; rate.num = (4 * 13e6) - rate.integer * 48; rate.den = 48; m_sample_rate = (double)4.0 * 13.0e6 / 48.0; if (bladerf_set_rational_sample_rate(bdev, BLADERF_MODULE_RX, &rate, &actual)) { printf("Error setting RX sampling rate\n"); return -1; } if(g_verbosity > 1) { fprintf(stderr, "Decimation : %u\n", m_decimation); fprintf(stderr, "Sample rate: %f\n", m_sample_rate); } } set_gain(0.45); return 0; } #define USB_PACKET_SIZE 512 int bladeRF_source::fill(unsigned int num_samples, unsigned int *overrun_i) { bool overrun; unsigned char ubuf[USB_PACKET_SIZE]; short *s = (short *)ubuf; unsigned int i, j, space, overruns = 0; complex *c; while((m_cb->data_available() < num_samples) && (m_cb->space_available() > 0)) { // read one usb packet from the bladeRF pthread_mutex_lock(&m_u_mutex); bladerf_sync_rx(bdev, ubuf, 512 / 4, NULL, 0); overrun = false; pthread_mutex_unlock(&m_u_mutex); if(overrun) overruns++; // write complex<short> input to complex<float> output c = (complex *)m_cb->poke(&space); // set space to number of complex items to copy if(space > (USB_PACKET_SIZE >> 2)) space = USB_PACKET_SIZE >> 2; // write data for(i = 0, j = 0; i < space; i += 1, j += 2) c[i] = complex(s[j], s[j + 1]); // update cb m_cb->wrote(i); } // if the cb is full, we left behind data from the usb packet if(m_cb->space_available() == 0) { fprintf(stderr, "warning: local overrun\n"); overruns++; } if(overrun_i) *overrun_i = overruns; return 0; } int bladeRF_source::read(complex *buf, unsigned int num_samples, unsigned int *samples_read) { unsigned int n; if(fill(num_samples, 0)) return -1; n = m_cb->read(buf, num_samples); if(samples_read) *samples_read = n; return 0; } /* * Don't hold a lock on this and use the bladeRF at the same time. */ circular_buffer *bladeRF_source::get_buffer() { return m_cb; } int bladeRF_source::flush(unsigned int flush_count) { m_cb->flush(); fill(flush_count * USB_PACKET_SIZE, 0); m_cb->flush(); return 0; }
Nuand/kalibrate-bladeRF
src/bladeRF_source.cc
C++
bsd-2-clause
7,808
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('api', '0002_auto_20150326_1433'), ] operations = [ migrations.RemoveField( model_name='problem', name='id', ), migrations.AlterField( model_name='problem', name='problemId', field=models.IntegerField(serialize=False, primary_key=True), preserve_default=True, ), ]
shanzi/tchelper
api/migrations/0003_auto_20150326_1435.py
Python
bsd-2-clause
560
/////////////////////////////////////////////////////////////////////////////// // // This file is part of libntfslinks. // // Copyright (c) 2014, Jean-Philippe Steinmetz // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * 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. // // 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 HOLDER 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. /////////////////////////////////////////////////////////////////////////////// #include "CharUtils.h" #include <strsafe.h> namespace libntfslinks { /** * Utilty function for converting a WCHAR string to a TCHAR string. */ bool WCHARtoTCHAR(WCHAR* src, size_t srcSize, TCHAR* dest, size_t destSize) { #ifdef UNICODE return StringCchCopy(dest, min(srcSize+1, destSize), (TCHAR*)src) == S_OK; #else return WideCharToMultiByte(CP_UTF8, 0, src, (int)srcSize, dest, (int)destSize, NULL, NULL) != 0; #endif } /** * Utility function for converting a TCHAR string to a WCHAR string. */ bool TCHARtoWCHAR(TCHAR* src, size_t srcSize, WCHAR* dest, size_t destSize) { #ifdef UNICODE return StringCchCopy(dest, min(srcSize+1, destSize), (TCHAR*)src) == S_OK; #else return MultiByteToWideChar(CP_UTF8, 0, src, (int)srcSize, dest, (int)destSize) != 0; #endif } } // namespace libntfslinks
caskater4/libntfslinks
libntfslinks/source/CharUtils.cpp
C++
bsd-2-clause
2,446
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace UserVoice.Voice { /// <summary> /// ユーザークラスです。184とそれ以外を区別するために使います。 /// </summary> [Serializable()] public class UserInfo : IEquatable<UserInfo>, IComparable<UserInfo>, IComparable { /// <summary> /// ユーザーIDを取得します。 /// </summary> public string UserId { get; set; } /// <summary> /// 184ユーザーか取得します。 /// </summary> public bool IsAnonymous { get { if (string.IsNullOrEmpty(this.UserId)) { return true; } return !this.UserId.All(c => char.IsDigit(c)); } } /// <summary> /// オブジェクトの比較を行います。 /// </summary> public int CompareTo(object other) { var obj = other as UserInfo; if (obj == null) { return -1; } return CompareTo(obj); } /// <summary> /// オブジェクトの比較を行います。 /// </summary> public int CompareTo(UserInfo other) { if (this.IsAnonymous != other.IsAnonymous) { return (this.IsAnonymous ? +1 : -1); } return this.UserId.CompareTo(other.UserId); } /// <summary> /// 文字列に変換します。 /// </summary> public override string ToString() { return this.UserId; } /// <summary> /// オブジェクトの等値性を判断します。 /// </summary> public override bool Equals(object obj) { var other = obj as UserInfo; if (other == null) { return false; } return Equals(other); } /// <summary> /// オブジェクトの等値性を判断します。 /// </summary> public bool Equals(UserInfo other) { if (other == null) { return false; } return this.UserId.Equals(other.UserId); } /// <summary> /// ハッシュコードを取得します。 /// </summary> public override int GetHashCode() { if (this.UserId == null) { return "".GetHashCode(); } return this.UserId.GetHashCode(); } /// <summary> /// コンストラクタ /// </summary> public UserInfo(string userId) { this.UserId = userId; } /// <summary> /// コンストラクタ /// </summary> public UserInfo() { } } }
ebifrier/UserVoice
UserVoice/Voice/UserInfo.cs
C#
bsd-2-clause
3,206
/* This file is part of VROOM. Copyright (c) 2015-2021, Julien Coupey. All rights reserved (see LICENSE). */ #include "problems/vrptw/operators/intra_mixed_exchange.h" namespace vroom { namespace vrptw { IntraMixedExchange::IntraMixedExchange(const Input& input, const utils::SolutionState& sol_state, TWRoute& tw_s_route, Index s_vehicle, Index s_rank, Index t_rank, bool check_t_reverse) : cvrp::IntraMixedExchange(input, sol_state, static_cast<RawRoute&>(tw_s_route), s_vehicle, s_rank, t_rank, check_t_reverse), _tw_s_route(tw_s_route) { } bool IntraMixedExchange::is_valid() { bool valid = cvrp::IntraMixedExchange::is_valid(); if (valid) { s_is_normal_valid = s_is_normal_valid && _tw_s_route.is_valid_addition_for_tw(_input, _moved_jobs.begin(), _moved_jobs.end(), _first_rank, _last_rank); if (check_t_reverse) { std::swap(_moved_jobs[_t_edge_first], _moved_jobs[_t_edge_last]); s_is_reverse_valid = s_is_reverse_valid && _tw_s_route.is_valid_addition_for_tw(_input, _moved_jobs.begin(), _moved_jobs.end(), _first_rank, _last_rank); // Reset to initial situation before potential application. std::swap(_moved_jobs[_t_edge_first], _moved_jobs[_t_edge_last]); } valid = s_is_normal_valid or s_is_reverse_valid; } return valid; } void IntraMixedExchange::apply() { assert(!reverse_t_edge or (_input.jobs[t_route[t_rank]].type == JOB_TYPE::SINGLE and _input.jobs[t_route[t_rank + 1]].type == JOB_TYPE::SINGLE)); if (reverse_t_edge) { std::swap(_moved_jobs[_t_edge_first], _moved_jobs[_t_edge_last]); } _tw_s_route.replace(_input, _moved_jobs.begin(), _moved_jobs.end(), _first_rank, _last_rank); } std::vector<Index> IntraMixedExchange::addition_candidates() const { return {s_vehicle}; } } // namespace vrptw } // namespace vroom
jcoupey/vroom
src/problems/vrptw/operators/intra_mixed_exchange.cpp
C++
bsd-2-clause
2,717
# DO NOT EDIT THIS FILE. This file will be overwritten when re-running go-raml. from app import app import gevent from gevent.pywsgi import WSGIServer from gevent.pool import Pool from gevent import monkey import signal monkey.patch_all() server = WSGIServer(('', 5000), app, spawn=Pool(None)) def stop(): server.stop() gevent.signal(signal.SIGINT, stop) if __name__ == "__main__": server.serve_forever()
Jumpscale/go-raml
codegen/fixtures/congo/python_server/server.py
Python
bsd-2-clause
425
<?php namespace Prajna\Components; use \Prajna\Traits\XmlRpcHelper; class Secret { use XmlRpcHelper; protected $session_id; public function __construct($client){ $this->client = $client; $this->session_id = $this->client->session_id; } public function get_all(){ return $this->doCall('secret.get_all',array( $this->session_id )); } public function get_all_records(){ return $this->doCall('secret.get_all_records',array( $this->session_id )); } public function get_uuid($secret){ return $this->doCall('secret.get_uuid',array( $this->session_id, $secret )); } public function get_value($secret){ return $this->doCall('secret.get_value',array( $this->session_id, $secret )); } public function set_value($secret,$value){ return $this->doCall('secret.set_value',array( $this->session_id, $secret, $value )); } public function get_other_config($secret){ return $this->doCall('secret.get_other_config',array( $this->session_id, $secret )); } public function set_other_config($secret,Array $config){ return $this->doCall('secret.set_other_config',array( $this->session_id, $secret, $config )); } public function add_to_other_config($secret,$key,$value){ return $this->doCall('secret.add_to_other_config',array( $this->session_id, $secret, $key, $value )); } public function remove_from_other_config($secret,$key){ return $this->doCall('secret.remove_from_other_config',array( $this->session_id, $secret, $key )); } public function create($PIF,$args){ return $this->doCall('secret.create',array( $this->session_id, $args )); } public function destroy($secret){ return $this->doCall('secret.destroy',array( $this->session_id, $secret )); } public function get_by_uuid($uuid){ return $this->doCall('secret.get_by_uuid',array( $this->session_id, $uuid )); } public function get_record($secret){ return $this->doCall('secret.get_record',array( $this->session_id, $secret )); } }
cameronjacobson/Prajna
src/Prajna/Components/Secret.php
PHP
bsd-2-clause
2,237
# frozen_string_literal: true # See LICENSE.txt for license module Ansible module Ruby module Parser class OptionData attr_reader :types, :name, :description, :choices def initialize(name:, description:, required:, types:, choices:) @types = types @description = description @name = name @required = required @choices = choices end def required? @required end end end end end
wied03/ansible-ruby
util/parser/option_data.rb
Ruby
bsd-2-clause
503
package main import ( "fmt" "log" "os" "reflect" "github.com/davidscholberg/go-i3barjson" "github.com/davidscholberg/goblocks/lib/modules" ) func main() { errLogger := log.New(os.Stderr, "error: ", 0) gb, err := modules.NewGoblocks() if err != nil { errLogger.Fatalln(err) } h := i3barjson.Header{Version: 1} err = i3barjson.Init(os.Stdout, nil, h, gb.Cfg.Global.Debug) if err != nil { errLogger.Fatalln(err) } // send the first statusLine err = i3barjson.Update(gb.StatusLine) if err != nil { errLogger.Fatalln(err) } shouldRefresh := false for { // select on all chans i, _, _ := reflect.Select(gb.SelectCases.Cases) selectReturn := gb.SelectCases.Actions[i](gb.SelectCases.Blocks[i]) if selectReturn.Exit { fmt.Println("") break } if selectReturn.SignalRefresh { shouldRefresh = true } else if selectReturn.Refresh { if shouldRefresh { err = i3barjson.Update(gb.StatusLine) if err != nil { errLogger.Fatalln(err) } shouldRefresh = false } } else if selectReturn.ForceRefresh { err = i3barjson.Update(gb.StatusLine) if err != nil { errLogger.Fatalln(err) } shouldRefresh = false } else if selectReturn.Reload { gb.Reset() gb, err = modules.NewGoblocks() if err != nil { errLogger.Fatalln(err) } err = i3barjson.Update(gb.StatusLine) if err != nil { errLogger.Fatalln(err) } shouldRefresh = false } } }
davidscholberg/goblocks
goblocks.go
GO
bsd-2-clause
1,443
var middleware = require('../../middleware') ; function handler (req, res, next) { var profile = { }; res.send(200, res.profile); next( ); return; } var endpoint = { path: '/users/:user/create' , method: 'get' , handler: handler }; module.exports = function configure (opts, server) { function mount (server) { server.get(endpoint.path, endpoint.middleware, updateUser, endpoint.handler); } var userInfo = middleware.minUser(opts, server); var mandatory = middleware.mandatory(opts, server); endpoint.middleware = mandatory.concat(userInfo); function updateUser (req, res, next) { var profile = { }; var name = req.params.user; var update = req.params; server.updateUser(name, update, {save:false, create:true}, function (result) { server.log.debug('UPDATED user', arguments); res.profile = result; next( ); }); } endpoint.mount = mount; return endpoint; }; module.exports.endpoint = endpoint;
bewest/restify-git-json
lib/handlers/users/create.js
JavaScript
bsd-2-clause
976
""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True
Varbin/EEH
_vendor/ldap3/protocol/formatters/validators.py
Python
bsd-2-clause
5,077
/*********************************************************************** Copyright (c) 2014, Carnegie Mellon University All rights reserved. Authors: Jennifer King <jeking04@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 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. 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 HOLDER 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. *************************************************************************/ #include <boost/make_shared.hpp> #include <or_ompl/TSRRobot.h> #include <or_ompl/or_conversions.h> using namespace or_ompl; TSRRobot::TSRRobot(const std::vector<TSR::Ptr> &tsrs, const OpenRAVE::EnvironmentBasePtr &penv) : _tsrs(tsrs), _penv(penv), _initialized(false), _solver("GeneralIK") { } bool TSRRobot::construct() { if(_initialized){ RAVELOG_ERROR("[TSRRobot] Already initialized. TSRRobot::construct cannot be called twice."); throw OpenRAVE::openrave_exception( "TSRRobot::construct cannot be called twice", OpenRAVE::ORE_Failed ); } _initialized = false; // Create an emtpy robot of the correct type _probot = RaveCreateRobot(_penv, "GenericRobot"); if( _probot.get() == NULL ){ RAVELOG_ERROR("[TSRRobot] Failed to create robot of type GenericRobot"); return _initialized; } // TODO: mimic body // Build the robot std::vector<OpenRAVE::KinBody::LinkInfoConstPtr> link_infos; std::vector<OpenRAVE::KinBody::JointInfoConstPtr> joint_infos; std::vector<OpenRAVE::RobotBase::ManipulatorInfoConstPtr> manip_infos; std::vector<OpenRAVE::RobotBase::AttachedSensorInfoConstPtr> sensor_infos; const std::string bodyprefix = "Body"; int bodynumber = 1; Eigen::Affine3d Tw0_e = Eigen::Affine3d::Identity(); for(unsigned int i=0; i < _tsrs.size(); i++){ TSR::Ptr tsr = _tsrs[i]; Eigen::Matrix<double, 6, 2> Bw = tsr->getBounds(); if (tsr->relative_body_name() != "NULL") { RAVELOG_ERROR("[TSRRobot] ERROR: TSRs relative to a body is not supported.\n"); return _initialized; } for(int j=0; j < 6; j++){ // Don't add a body if there is no freedom in this dimension if(Bw(j,0) == 0.0 && Bw(j,1) == 0.0){ continue; } // If the bounds are equal and non-zero, we should do something reasonable // For now, this isn't supported if(Bw(j,0) == Bw(j,1)){ RAVELOG_ERROR("[TSRRobot] ERROR: TSR Chains are currently unable to deal with cases where two bounds are equal but non-zero, cannot robotize.\n"); return _initialized; } // Check for axis flip, marked by Bw values being backwards bool bFlipAxis = false; if(Bw(j,0) > Bw(j,1)){ Bw(j,0) = -Bw(j,0); Bw(j,1) = -Bw(j,1); bFlipAxis = true; } // TODO: Handle mimic joints // Store joint limits _lowerlimits.push_back(Bw(j,0)); _upperlimits.push_back(Bw(j,1)); // Create a Link std::string prev_bodyname = (boost::format("%s%d") % bodyprefix % (bodynumber-1)).str(); std::string bodyname = (boost::format("%s%d") % bodyprefix % bodynumber).str(); OpenRAVE::KinBody::LinkInfoPtr link_info = boost::make_shared<OpenRAVE::KinBody::LinkInfo>(); link_info->_name = bodyname; link_info->_t = toOR<double>(Tw0_e); // transform OpenRAVE::KinBody::GeometryInfoPtr geom_info = boost::make_shared<OpenRAVE::KinBody::GeometryInfo>(); if(j < 3){ geom_info->_type = OpenRAVE::GT_Box; }else{ geom_info->_type = OpenRAVE::GT_Cylinder; geom_info->_vGeomData = OpenRAVE::Vector(0.03, 0.07, 0.0); //cylinder radius, height, ignored } if(j == 0){ geom_info->_vGeomData = OpenRAVE::Vector(0.04, 0.02, 0.02); // box extents }else if(j == 1){ geom_info->_vGeomData = OpenRAVE::Vector(0.02, 0.04, 0.02); // box extents }else if(j == 2){ geom_info->_vGeomData = OpenRAVE::Vector(0.02, 0.02, 0.04); // box extents }else if(j == 3){ OpenRAVE::RaveTransformMatrix<OpenRAVE::dReal> t = OpenRAVE::geometry::matrixFromAxisAngle(OpenRAVE::Vector(0, 0, 1), 90.); geom_info->_t = t; }else if(j == 4){ OpenRAVE::RaveTransformMatrix<OpenRAVE::dReal> t = OpenRAVE::geometry::matrixFromAxisAngle(OpenRAVE::Vector(0, 1, 0), 90.); geom_info->_t = t; }else if(j == 5){ OpenRAVE::RaveTransformMatrix<OpenRAVE::dReal> t = OpenRAVE::geometry::matrixFromAxisAngle(OpenRAVE::Vector(1, 0, 0), 90.); geom_info->_t = t; } geom_info->_vDiffuseColor = OpenRAVE::Vector(0.3, 0.7, 0.3); link_info->_vgeometryinfos.push_back(geom_info); link_infos.push_back(link_info); // Now create a joint OpenRAVE::KinBody::JointInfoPtr joint_info = boost::make_shared<OpenRAVE::KinBody::JointInfo>(); std::string joint_name = (boost::format("J%d") % bodynumber).str(); joint_info->_name = joint_name; if(j < 3){ joint_info->_type = OpenRAVE::KinBody::JointSlider; }else{ joint_info->_type = OpenRAVE::KinBody::JointHinge; } joint_info->_linkname0 = prev_bodyname; joint_info->_linkname1 = bodyname; joint_info->_vweights[0] = 1.; joint_info->_vmaxvel[0] = 1.; joint_info->_vresolution[0] = 1.; joint_info->_vlowerlimit[0] = Bw(j,0); joint_info->_vupperlimit[0] = Bw(j,1); joint_info->_vaxes[0] = OpenRAVE::Vector(0., 0., 0.); unsigned int aidx = (j % 3); if(j > 3 && bFlipAxis){ joint_info->_vaxes[0][aidx] = -1.; }else{ joint_info->_vaxes[0][aidx] = 1.; } joint_infos.push_back(joint_info); bodynumber++; } Tw0_e = Tw0_e * tsr->getEndEffectorOffsetTransform(); } _num_dof = bodynumber - 1; // now add a geometry to the last body with the offset of the last TSR, this will be the target for the manipulator TSR::Ptr last_tsr = _tsrs.back(); Tw0_e = last_tsr->getEndEffectorOffsetTransform(); OpenRAVE::KinBody::LinkInfoPtr link_info = boost::make_shared<OpenRAVE::KinBody::LinkInfo>(); std::string bodyname = (boost::format("%s%d") % bodyprefix % (bodynumber-1)).str(); link_info->_name = bodyname; link_info->_bStatic = false; OpenRAVE::KinBody::GeometryInfoPtr geom_info = boost::make_shared<OpenRAVE::KinBody::GeometryInfo>(); geom_info->_t = toOR<double>(Tw0_e); geom_info->_type = OpenRAVE::GT_Sphere; geom_info->_vGeomData = OpenRAVE::Vector(0.03, 0., 0.); //radius, ignored, ignored geom_info->_vDiffuseColor = OpenRAVE::Vector(0.3, 0.7, 0.3); link_info->_vgeometryinfos.push_back(geom_info); link_infos.push_back(link_info); if(bodynumber > 1){ _point_tsr = false; OpenRAVE::RobotBase::ManipulatorInfoPtr manip_info = boost::make_shared<OpenRAVE::RobotBase::ManipulatorInfo>(); manip_info->_name = "dummy"; manip_info->_sBaseLinkName = (boost::format("%s0") % bodyprefix).str(); manip_info->_sEffectorLinkName = bodyname; manip_infos.push_back(manip_info); }else{ _point_tsr = true; RAVELOG_DEBUG("[TSRRobot] This is a point TSR, no robotized TSR needed."); _initialized = true; return _initialized; } if(_point_tsr && _tsrs.size() != 1){ RAVELOG_ERROR("[TSRRobot] Can't yet handle case where the TSRChain has no freedom but multiple TSRs, try making it a chain of length 1.\n"); _initialized = false; return _initialized; } // If we made it this far, then we can build the robot. _probot->Init(link_infos, joint_infos, manip_infos, sensor_infos); // Set the name properly std::string robotname = (boost::format("TSRChain%lu") % (unsigned long int) this).str(); _probot->SetName(robotname); // Add it to the environment _penv->Add(_probot, true); // Set the pose // TODO: mimic joint stuff _probot->SetTransform(toOR<double>(_tsrs[0]->getOriginTransform())); // Create an IK Solver _ik_solver = OpenRAVE::RaveCreateIkSolver(_penv, _solver); if(_ik_solver.get() == NULL){ RAVELOG_ERROR("[TSRRobot] Cannot create IK solver, make sure you have the GeneralIK plugin loadable by OpenRAVE\n"); _initialized = false; return _initialized; } // Grab the active manipulator on our newly created robot OpenRAVE::RobotBase::ManipulatorPtr pmanip = _probot->GetActiveManipulator(); _ik_solver->Init(pmanip); // Finally, disable the robot so we don't do collision checking against it _probot->Enable(false); _initialized = true; return _initialized; } Eigen::Affine3d TSRRobot::findNearestFeasibleTransform(const Eigen::Affine3d &Ttarget) { OpenRAVE::Transform or_target = toOR<double>(Ttarget); if(_solver.compare("GeneralIK") != 0){ RAVELOG_ERROR("[TSRRobot] Only GeneralIK solver supported."); throw OpenRAVE::openrave_exception( "Only GeneralIK solver supported.", OpenRAVE::ORE_Failed ); } // Setup the free parameters - the format and meaning of these is defined directly by // the IK solver - in our case GeneralIK std::vector<OpenRAVE::dReal> ikfreeparams; ikfreeparams.resize(12); ikfreeparams[0] = 1; // The number of targets - in this case always 1 ikfreeparams[1] = 0; // The manipulator associated the target - only one manipulator to always 0 // Pose of target ikfreeparams[2] = or_target.rot.x; ikfreeparams[3] = or_target.rot.y; ikfreeparams[4] = or_target.rot.z; ikfreeparams[5] = or_target.rot.w; ikfreeparams[6] = or_target.trans.x; ikfreeparams[7] = or_target.trans.y; ikfreeparams[8] = or_target.trans.z; ikfreeparams[9] = 0; // no balancing ikfreeparams[10] = 0; // junk parameters - mode in previous versions of GeneralIK ikfreeparams[11] = 0; // not translation only - aka do rotation std::vector<OpenRAVE::dReal> q0; boost::shared_ptr<std::vector<OpenRAVE::dReal> > solution = boost::make_shared<std::vector<OpenRAVE::dReal> >(); // solve ik _ik_solver->Solve(OpenRAVE::IkParameterization(), q0, ikfreeparams, OpenRAVE::IKFO_IgnoreSelfCollisions, solution); // Set the dof values to the solution and grab the end-effector transform in world coordinates _probot->SetDOFValues(*solution); Eigen::Affine3d ee_pose = toEigen(_probot->GetActiveManipulator()->GetEndEffectorTransform()); // Convert to proper frame Eigen::Affine3d closest = ee_pose * _tsrs.back()->getEndEffectorOffsetTransform(); return closest; }
personalrobotics/or_ompl
src/TSRRobot.cpp
C++
bsd-2-clause
12,546
#!/usr/bin/env python """ LeBLEU - Letter-edit / Levenshtein BLEU """ import logging #__all__ = [] __version__ = '0.0.1' __author__ = 'Stig-Arne Gronroos' __author_email__ = "stig-arne.gronroos@aalto.fi" _logger = logging.getLogger(__name__) def get_version(): return __version__ # The public api imports need to be at the end of the file, # so that the package global names are available to the modules # when they are imported. from .lebleu import LeBLEU # Convenience functions def eval_single(*args, **kwargs): lb = LeBLEU(**kwargs) return lb.eval_single(*args) def eval(*args, **kwargs): lb = LeBLEU(**kwargs) return lb.eval(*args)
Waino/LeBLEU
lebleu/__init__.py
Python
bsd-2-clause
670
if(!org) var org={}; if(!org.judison) org.judison={}; if(!org.judison.bmsp) org.judison.bmsp={}; with(org.judison.bmsp){ init = function(){ document.getElementById("bookmarks-view").place = "place:queryType=1&folder=" + window.top.PlacesUtils.bookmarksMenuFolderId; } }
judison/bmsp
src/content/overlay.js
JavaScript
bsd-2-clause
290
<? # $Id: new-user.php,v 1.1.2.7 2002-05-18 08:25:09 dan Exp $ # # Copyright (c) 1998-2002 DVL Software Limited $origin = $_GET["origin"]; ?> <form action="<?php echo $_SERVER["PHP_SELF"] . "?origin=" . $origin ?>" method="POST" NAME=f> <TABLE width="*" border="0" cellpadding="1"> <TR> <TD VALIGN="top"> <? if (!$Customize) { ?> <INPUT TYPE="hidden" NAME="ADD" VALUE="1"> User ID:<br> <INPUT SIZE="15" NAME="UserLogin" VALUE="<? echo $UserLogin ?>"><br><br> <? } ?> Password:<br> <INPUT TYPE="PASSWORD" NAME="Password1" VALUE="<?echo $Password1 ?>" size="20"><br><br> Confirm Password:<br> <INPUT TYPE="PASSWORD" NAME="Password2" VALUE="<?echo $Password2 ?>" size="20"> </TD> <TD VALIGN="top"> email address (required):<br> <INPUT SIZE="35" NAME="email" VALUE="<?echo $email ?>"> Number of Days to show in side-bar: <SELECT NAME="numberofdays" size="1"> <OPTION <? if ($numberofdays == "0") echo "selected " ?> VALUE="0">0</OPTION> <OPTION <? if ($numberofdays == "1") echo "selected " ?> VALUE="1">1</OPTION> <OPTION <? if ($numberofdays == "2") echo "selected " ?> VALUE="2">2</OPTION> <OPTION <? if ($numberofdays == "3") echo "selected " ?> VALUE="3">3</OPTION> <OPTION <? if ($numberofdays == "4") echo "selected " ?> VALUE="4">4</OPTION> <OPTION <? if ($numberofdays == "5") echo "selected " ?> VALUE="5">5</OPTION> <OPTION <? if ($numberofdays == "6") echo "selected " ?> VALUE="6">6</OPTION> <OPTION <? if ($numberofdays == "7") echo "selected " ?> VALUE="7">7</OPTION> <OPTION <? if ($numberofdays == "8") echo "selected " ?> VALUE="8">8</OPTION> <OPTION <? if ($numberofdays == "9") echo "selected " ?> VALUE="9">9</OPTION> </SELECT> <br><br> <INPUT TYPE="checkbox" NAME="emailsitenotices_yn" VALUE="ON" <? if ($emailsitenotices_yn == "ON") {echo " checked";}?>>Put me on the announcement mailing list (low volume)<br> <br> We can send you an email when something on your watch list changes.<br> Send me, at most, one message per: <SELECT NAME="watchnotifyfrequency" size="1"> <OPTION <? if ($watchnotifyfrequency == "Z") echo "selected " ?> VALUE="Z">Don't notify me</OPTION> <OPTION <? if ($watchnotifyfrequency == "D") echo "selected " ?> VALUE="D">Day</OPTION> <OPTION <? if ($watchnotifyfrequency == "W") echo "selected " ?> VALUE="W">Week (on Tuesdays)</OPTION> <OPTION <? if ($watchnotifyfrequency == "F") echo "selected " ?> VALUE="F">Fortnight (9th and 23rd)</OPTION> <OPTION <? if ($watchnotifyfrequency == "M") echo "selected " ?> VALUE="M">Month (23rd)</OPTION> </SELECT> <br><br> <INPUT TYPE="submit" VALUE="<? if ($Customize) { echo "update";} else { echo "create";} ?> account" NAME="submit"> <INPUT TYPE="reset" VALUE="reset form"> </TD> </TR> </TABLE> </FORM>
lattera/freshports
include/tags/FreshPorts2_Launch/new-user.php
PHP
bsd-2-clause
3,014
//////////////////////////////////////////////////////////////////////////////////////////////////////// // Part of Injectable Generic Camera System // Copyright(c) 2017, Frans Bouma // All rights reserved. // https://github.com/FransBouma/InjectableGenericCameraSystem // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met : // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * 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. // // 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 HOLDER 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. //////////////////////////////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Globals.h" #include "GameConstants.h" //-------------------------------------------------------------------------------------------------------------------------------- // data shared with asm functions. This is allocated here, 'C' style and not in some datastructure as passing that to // MASM is rather tedious. extern "C" { uint8_t g_cameraEnabled = 0; float g_fovValue = DEFAULT_FOV_DEGREES; } namespace IGCS { Globals::Globals() { } Globals::~Globals() { } Globals &Globals::instance() { static Globals theInstance; return theInstance; } }
FransBouma/InjectableGenericCameraSystem
Cameras/BulletstormFCE/InjectableGenericCameraSystem/Globals.cpp
C++
bsd-2-clause
2,277
<? # $Id: confirmation.php,v 1.1.2.4 2002-05-22 04:30:21 dan Exp $ # # Copyright (c) 1998-2002 DVL Software Limited require($_SERVER['DOCUMENT_ROOT'] . "/include/common.php"); require($_SERVER['DOCUMENT_ROOT'] . "/include/freshports.php"); require($_SERVER['DOCUMENT_ROOT'] . "/include/databaselogin.php"); require($_SERVER['DOCUMENT_ROOT'] . "/include/getvalues.php"); freshports_Start("Account confirmation", "freshports - new ports, applications", "FreeBSD, index, applications, ports"); $Debug = 0; $ResultConfirm = 999; $token = $_GET["token"]; if (IsSet($token)) { $token = AddSlashes($token); if ($Debug) echo "I'm confirming with token $token\n<BR>"; $sql = "select ConfirmUserAccount('$token')"; $result = pg_exec($db, $sql); if ($result) { $row = pg_fetch_array($result,0); $ResultConfirm = $row[0]; } else { echo pg_errormessage() . $sql; } } ?> <TABLE WIDTH="<? echo $TableWidth; ?>" BORDER="0" ALIGN="center"> <tr><td VALIGN=TOP> <TABLE WIDTH="100%"> <TR> <? freshports_PageBannerText("Account confirmation"); ?> </TR> <TR><TD> <P> <? if ($Debug) echo $ResultConfirm; switch ($ResultConfirm) { case 0: echo "I don't know anything about that token."; break; case 1: echo 'Your account has been enabled. Please proceed to the <A HREF="login.php">login page</A>'; break; case 2: echo "Well. This just isn't supposed to happen. For some strange and very rare reason, there is more than one person with that token.<BR><BR>Please contact webmaster&#64;freshports.org for help."; break; case -1: echo "An error has occurred. Sorry."; break; case 999: echo "Hi there. What you are doing here?"; break; default: } ?> </P> </TD></TR> </table> </td> <td valign="top" width="*"> <? include($_SERVER['DOCUMENT_ROOT'] . "/include/side-bars.php"); ?> </td> </tr> </table> <TABLE WIDTH="<? echo $TableWidth; ?>" BORDER="0" ALIGN="center"> <TR><TD> <? include($_SERVER['DOCUMENT_ROOT'] . "/include/footer.php") ?> </TD></TR> </TABLE> </body> </html>
lattera/freshports
www/tags/FreshPorts2_Launch/confirmation.php
PHP
bsd-2-clause
2,095
<?php namespace hlin\tools; /** * @copyright (c) 2014, freia Team * @license BSD-2 <http://freialib.github.io/license.txt> * @package freia Library */ class HoneypotCommand implements \hlin\archetype\Command { use \hlin\CommandTrait; /** * @return int */ function main(array $args = null) { $cli = $this->cli; $fs = $this->fs; $autoloader = $this->context->autoloader(); if ($autoloader === null) { throw new Panic('Honeypot command requires autoloader to be defined in context.'); } $paths = $autoloader->paths(); $namespaces = array_keys($paths); $cachepath = $this->context->path('cachepath', true); if ($cachepath == null) { $cli->printf("The cachepath path is not defined in the current system.\n"); return 500; } if (count($args) > 0) { foreach ($args as $namespace) { if (in_array($namespace, $namespaces)) { $file = $this->generate_honeypot($namespace, $paths[$namespace]); $honeypotpath = "$cachepath/honeypots"; if ( ! $fs->file_exists($honeypotpath)) { $fs->mkdir($honeypotpath, 0770, true); } $fs->file_put_contents("$cachepath/honeypots/$namespace.php", $file); $cli->printf(" -> $namespace\n"); } } return 0; } else { // regenerate all foreach ($paths as $namespace => $path) { $file = $this->generate_honeypot($namespace, $path); $honeypotpath = "$cachepath/honeypots"; if ( ! $fs->file_exists($honeypotpath)) { $fs->mkdir($honeypotpath, 0770, true); } $fs->file_put_contents("$cachepath/honeypots/$namespace.php", $file); $cli->printf(" -> $namespace\n"); } return 0; } } // ---- Private --------------------------------------------------------------- /** * @return string */ function generate_honeypot($namespace, $path) { $fs = $this->fs; $classes = []; $traits = []; $dirs = $fs->glob("$path/src/*", GLOB_ONLYDIR); foreach ($dirs as $dir) { $dir = $fs->basename($dir); $symbols = $fs->glob("$path/src/$dir/*.php"); foreach ($symbols as $symbol) { $basename = preg_replace('/\.php$/', '', str_replace("$path/src/$dir/", '', $symbol)); if ($dir == 'Trait') { $traits[] = "$basename$dir"; } else { // not a trait // check if interface (interfaces must always be explicit) $symbolname = \hlin\PHP::pnn("$namespace.$basename$dir"); if ( ! interface_exists($symbolname, true)) { $classes[] = "$basename$dir"; } } } } $symbols = $fs->glob("$path/src/*.php"); foreach ($symbols as $symbol) { $basename = preg_replace('/\.php$/', '', str_replace("$path/src/", '', $symbol)); // check if interface (interfaces must always be explicit) $symbolname = \hlin\PHP::pnn("$namespace.$basename"); if ( ! interface_exists($symbolname, true)) { $classes[] = "$basename"; } } $ptr = stripos($namespace, '.'); $basenamespace = ltrim(\hlin\PHP::pnn(substr($namespace, 0, $ptr)), '\\'); $simplenamespace = ltrim(\hlin\PHP::pnn(substr($namespace, $ptr + 1)), '\\'); $honeypot = "<?php # autocomplete IDE honeypot\n\n"; $honeypot .= "namespace $basenamespace;\n\n"; if ( ! empty($classes)) { $honeypot .= "// classes\n"; foreach ($classes as $class) { $honeypot .= sprintf("class %-25s extends $simplenamespace\\$class {}\n", $class); } $honeypot .= "\n"; } if ( ! empty($traits)) { $honeypot .= "// traits\n"; foreach ($traits as $trait) { $honeypot .= sprintf("trait %-25s { use $simplenamespace\\$trait; }\n", $trait); } $honeypot .= "\n"; } return $honeypot; } } # class
freialib/hlin.tools
src/Command/Honeypot.php
PHP
bsd-2-clause
3,593
package stallone.mc.pcca; import static stallone.api.API.*; import stallone.api.IAlgorithm; import stallone.api.algebra.Algebra; import stallone.api.algebra.IEigenvalueDecomposition; import stallone.api.cluster.IClustering; import stallone.api.doubles.Doubles; import stallone.api.doubles.IDoubleArray; import stallone.api.ints.IIntArray; import stallone.api.ints.Ints; import stallone.ints.PrimitiveIntArray; /** * A java implementation of the Inner Simplex Algorithm (ISA) from Marcus Weber. For details refer to:<br> * <i>Marcus Weber: Improved Perron Cluster Analysis, ZIB-Report 03-04.<br> * Marcus Weber and Tobias Galliat: Charakterization of Transition States in Conformational Dynamics using Fuzzy States, * ZIB-Report 02-12.</i><br> * See <tt><A HREF="www.zib.de/bib/pub/index.en.html"><CODE>www.zib.de/bib/pub/index.en.html</CODE></A></tt>. * * <p>A typical application is the computation of meta stable sets of a Markov chain represented by a given reversible * transition matrix. This requires the following steps:<br> * 1) Compute a reversible transition matrix, say <b>P</b>.<br> * 2) Determine the number of meta stable sets, for instance via the size of the Perron Cluster, say <i>k</i>.<br> * 3) Compute the <i>k</i> eigenvectors belonging to the <i>k</i> eigenvalues closest to 1.<br> * 4) Use the eigenvectors as input data to the cluster algorithm.<br> * 5) With {@link #getClusters} you get an array containing the allocation of each indices to a cluster, which is a * number between 0,...,k-1.<br> * 6) Use {@link #getPermutationArray} to obtain a permutation array. With this array you can permute the state space of * <b>P</b>, such that states belonging to the same cluster are neighbours.</p> * * @author meerbach@math.fu-berlin.de */ public final class PCCA implements IAlgorithm { /** * The condition of the transformation matrix. The transformation matrix transforms a given dataset with * simplex-like structure to a dataset with standard simplex-like structure. Large condition indicates an ill * conditioned cluster problem. */ //public double COND_TRANS; /** * An indikator for the deviation of the data-points from simplex structure. Is this indikator negative, than there * are data points outside the computed simplex, so this indikator should be close to zero. */ public double INDIKATOR; private int[] CLUSTER; private int[] SORTARRAY; private int[] CLUSTER_SIZE; private IDoubleArray FUZZY; private IDoubleArray eigenvectors; /** * Creates a new instance of ClusterByIsa and computes a clustering of a data set with the Isa-algorithm. The * created instance will be immutable. The results will be:<br> * <i>Cluster allocation</i>: An integer array containing the allocation of the given data points to the clusters: * <code>CLUSTER[i]</code> is the cluster of data point <i>i</i>.<br> * <i>Fuzzy allocations</i>: A (number of data points times number of clusters) -matrix containing the fuzzy * allocation for each data point.<br> * <i>Simplex indikator</i>: An indikator for the deviation of the shape of the set of data-points from a simplex * structure.<br> * <i>Condition indikator</i>: Large condition indicates an ill conditioned cluster problem.<br> * Use the {@link #allData()} method to display all results and the {@link #getClusters()}, resp. {@link #getFuzzy} * method to achieve them. The simplex and the condition indikator are public fields. * * @param dataSet the data points in a <code>DoubleMatrix2D</code>. <code>dataSet.rows()</code> is the number of * data points, while <code>dataSet.columns()</code> is the number of cluster. * * @throws IllegalArgumentException if there are more clusters than data points. */ public PCCA() { } public void setEigenvectors(IDoubleArray dataSet) { this.eigenvectors = dataSet; } public void perform() { if (eigenvectors == null) { throw new RuntimeException("No eigenvectors set. Aborting."); } /* initialisation */ int noOfClusters = eigenvectors.columns(); int noOfPoints = eigenvectors.rows(); IDoubleArray fuzzyAllocation; IDoubleArray transMatrix; double condTrans; double indikator = 0; int[] clusterAllocation = new int[noOfPoints]; int[] counter; /* Special cases: */ /* a) less than two clusters. */ if (noOfClusters < 2) { fuzzyAllocation = Doubles.create.matrix(noOfPoints, 1, 1); transMatrix = Doubles.create.matrix(1, 1, 1 / eigenvectors.get(0, 0)); condTrans = 0; for (int i = 0; i < noOfPoints; i++) { clusterAllocation[i] = 0; } counter = new int[2]; counter[0] = 0; counter[1] = noOfPoints; } /* b) more cluster than states. */ else if (noOfClusters > noOfPoints) { throw new IllegalArgumentException("There are more clusters than points given!"); } else if (noOfClusters == noOfPoints) { fuzzyAllocation = Doubles.create.array(noOfPoints,noOfPoints); for (int i=0; i<fuzzyAllocation.rows(); i++) fuzzyAllocation.set(i,i,1); transMatrix = Algebra.util.inverse(eigenvectors); // currently, we do not calculate the condition number because we lack the method //condTrans = A.cond(transMatrix); counter = new int[noOfPoints + 1]; for (int i = 0; i < noOfPoints; i++) { clusterAllocation[i] = i; counter[i + 1] = 1; } } /* Start of the Isa-algorithm. */ else { double skalar = 0; double maxDist = 0; double comp = 0; double entry = 0; int[] index = new int[noOfClusters]; int[] indexAll = Ints.create.arrayRange(0, noOfClusters).getArray(); IDoubleArray orthoSys = eigenvectors.copy(); IDoubleArray dummy; /* Compute the two data-points with the largest distance *(quantified by the 2-norm)*/ for (int i = 0; i < noOfPoints; i++) { for (int j = i + 1; j < noOfPoints; j++) { double dij = Algebra.util.distance(eigenvectors.viewRow(i), eigenvectors.viewRow(j)); if (dij > maxDist) { maxDist = dij; index[0] = i; index[1] = j; } } } /* compute the other representatives by modified gram-schmidt * (i.e. the data points with the *largest distance to them computed before).*/ for (int i = 0; i < noOfPoints; i++) { for (int j=0; j<orthoSys.columns(); j++) orthoSys.set(i, j, orthoSys.get(i,j)-eigenvectors.get(0, j)); } // divide by norm of index 1. double d = Algebra.util.norm(orthoSys.viewRow(index[1])); Algebra.util.scale(1.0/d, orthoSys); // ?? for (int i = 2; i < noOfClusters; i++) { maxDist = 0; dummy = orthoSys.viewRow(index[i - 1]).copy(); for (int j = 0; j < noOfPoints; j++) { skalar = Algebra.util.dot(dummy, orthoSys.viewRow(j)); for (int k = 0; k<dummy.size(); k++) { orthoSys.set(j, k, orthoSys.get(j,k) - (dummy.get(k) * skalar)); } comp = Algebra.util.norm(orthoSys.viewRow(j)); if (comp > maxDist) { maxDist = comp; index[i] = j; } } double normi = Algebra.util.norm(orthoSys.viewRow(index[i])); Algebra.util.scale(1.0/normi, orthoSys); } /* Use the index-array with the representatives to compute the * transformation matrix, i.e., the matrix that maps the * representative to the edges of the standard simplex.*/ transMatrix = Algebra.util.inverse(eigenvectors.view(index, indexAll)); // currently cannot compute condition number //condTrans = A.cond(transMatrix); /* Transform the data set to a (hopefully) nearly standard simplex * structure, by mapping all data points with the computed * transformation matrix. */ fuzzyAllocation = Doubles.create.matrix(Algebra.util.product(eigenvectors, transMatrix).getTable()); /* Extract from soft (fuzzy) allocation the sharp allocation vektor.*/ counter = new int[noOfClusters + 1]; for (int i = 0; i < noOfPoints; i++) { comp = 0; for (int j = 0; j < noOfClusters; j++) { entry = fuzzyAllocation.get(i, j); if (entry < indikator) { indikator = entry; } if (entry > comp) { clusterAllocation[i] = j; comp = entry; } } counter[clusterAllocation[i] + 1]++; } } // end if-else /* Compute a sorting array and an array with the number of data points *in each cluster*/ int[] counter2 = new int[noOfClusters]; int[] sortarray = new int[noOfPoints]; for (int i = 1; i < counter.length; i++) { counter[i] += counter[i - 1]; } for (int i = 0; i < sortarray.length; i++) { sortarray[counter[clusterAllocation[i]] + counter2[clusterAllocation[i]]] = i; counter2[clusterAllocation[i]]++; } /* define fields */ INDIKATOR = indikator; FUZZY = fuzzyAllocation; //COND_TRANS = condTrans; CLUSTER = clusterAllocation; SORTARRAY = sortarray; CLUSTER_SIZE = counter2; } /** * Returns an array with cluster allocations. <code>int[i]</code> is the cluster to which data point i was * allocated. */ public IIntArray getClusters() { return(new PrimitiveIntArray(CLUSTER)); } /** * Returns an array containing the number of data points in each cluster. */ public IIntArray getClusterSize() { return(new PrimitiveIntArray(CLUSTER_SIZE)); } public IDoubleArray getFuzzy() { return(FUZZY); } /** * Returns the permutation which is needed to arrange the data points according to their cluster. */ public IIntArray getPermutationArray() { return(new PrimitiveIntArray(SORTARRAY)); } }
markovmodel/stallone
src/stallone/mc/pcca/PCCA.java
Java
bsd-2-clause
11,313
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using FlubuCore.Analyzers; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Text; namespace FlubuClore.Analyzer { [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(FlubuCloreAnalyzerCodeFixProvider))] [Shared] public class FlubuCloreAnalyzerCodeFixProvider : CodeFixProvider { private const string Title = "Make uppercase"; public sealed override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(TargetParameterAnalyzer.FirstParameterMustBeOfTypeITargetDiagnosticId); } } public sealed override FixAllProvider GetFixAllProvider() { // See https://github.com/dotnet/roslyn/blob/master/docs/analyzers/FixAllProvider.md for more information on Fix All Providers return WellKnownFixAllProviders.BatchFixer; } public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); // TODO: Replace the following code with your own analysis, generating a CodeAction for each fix to suggest var diagnostic = context.Diagnostics.First(); var diagnosticSpan = diagnostic.Location.SourceSpan; // Find the type declaration identified by the diagnostic. var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<TypeDeclarationSyntax>().First(); // Register a code action that will invoke the fix. context.RegisterCodeFix( CodeAction.Create( title: Title, createChangedSolution: c => MakeUppercaseAsync(context.Document, declaration, c), equivalenceKey: Title), diagnostic); } private async Task<Solution> MakeUppercaseAsync(Document document, TypeDeclarationSyntax typeDecl, CancellationToken cancellationToken) { // Compute new uppercase name. var identifierToken = typeDecl.Identifier; var newName = identifierToken.Text.ToUpperInvariant(); // Get the symbol representing the type to be renamed. var semanticModel = await document.GetSemanticModelAsync(cancellationToken); var typeSymbol = semanticModel.GetDeclaredSymbol(typeDecl, cancellationToken); // Produce a new solution that has all references to that type renamed, including the declaration. var originalSolution = document.Project.Solution; var optionSet = originalSolution.Workspace.Options; var newSolution = await Renamer.RenameSymbolAsync(document.Project.Solution, typeSymbol, newName, optionSet, cancellationToken).ConfigureAwait(false); // Return the new solution with the now-uppercase type name. return newSolution; } } }
flubu-core/flubu.core
src/FlubuCore.Analyzers/FlubuCloreAnalyzerCodeFixProvider.cs
C#
bsd-2-clause
3,365
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; console.log(process.env.NODE_ENV); ReactDOM.render(<App />, document.getElementById('root'));
freoff/zlecenia
src/index.js
JavaScript
bsd-2-clause
204
import cStringIO import zlib import wx #---------------------------------------------------------------------- def getMailData(): return zlib.decompress( "x\xda\x01M\x01\xb2\xfe\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00 \x00\ \x00\x00 \x08\x06\x00\x00\x00szz\xf4\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\ \x08d\x88\x00\x00\x01\x04IDATX\x85\xed\x941\x0e\x82@\x10E\x9f\xc6`,\x88\xad\ \x8d\x8d\x89r\x02B\xc1\t\xbc\x94\x857\xf04\x9e\xc0C\x00\x95\xb1\xb1\xa52\xda\ h\xc1N\xe1\xc8f5j\x9cD^Ev\x98\x81\xffv\x01::\xfe\x9d^\x91e\xd7\xb6\xc2d\xb9\ \x04`\xb8X\xbc\xf5\x80sY\x02p\xdcn[\xeb\xfd\xb7\xa6\x7f\x80\x81\xaf o<O\xd3f\ \xc1\x19y\x1a\xd7\xbf\xf7$\x17\xec\x19\x90\xbd?\x15\x05\x00\xd5z\r\xc0\\n\ \x08\x99p\x89\xa5o<\x9b\x010J\x12\xe0\xf1,\xd83\x10\xafV\xcd\x85K \x04M\x04\ \x92\xcb\\\xfb\x06\x84\xa7M\xa8u_r\x1fv\r\x08\xb1\xfc\x07\x14\x952\xf3\x90\ \xdc\xd3\xa71l\xe0p\x00\xe0R\xd7@8\x91N.}\x91\x9b\xc3t\xda\xdag\xd0\x80$\xdf\ \xed\x00\x88\xf2\xbcYw\tb\xf9\xfe\xd5\x19\xd0\xa7=\xf2\xcdQ\xd83\xe0K\xae\t}\ \xdf\xd2'sd\xae\xc6\x9e\x81P\xf2\x97Q&\xd8l\xee\xca\xf6\x0c\xf8\xf6\xea[\xfc\ \xdc@G\xc7\rv\x18V\xd3#+\xef\x8c\x00\x00\x00\x00IEND\xaeB`\x82\xb38\x8e\xb0"\ ) def getMailBitmap(): return wx.BitmapFromImage(getMailImage()) def getMailImage(): stream = cStringIO.StringIO(getMailData()) return wx.ImageFromStream(stream) def getMailIcon(): icon = wx.EmptyIcon() icon.CopyFromBitmap(getMailBitmap()) return icon #---------------------------------------------------------------------- def getNoMailData(): return zlib.decompress( 'x\xda\x01G\x04\xb8\xfb\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00 \x00\ \x00\x00 \x08\x06\x00\x00\x00szz\xf4\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\ \x08d\x88\x00\x00\x03\xfeIDATX\x85\xed\x97[o\xdb8\x10F\x0fu\xa1$\xeb\x96(A\ \x92\x1a}\xe8\xcf\xdc\xdd?\xeb\xa0h\x12\'\xa9#;\xba\x8b\x12\xb5\x0f\x81\x88\ \xba\xb6w\xb37\xf4a;\x80!\x98\xb09gf8\xdfPBX6?\xd2\xac\x1f\xea\xfd\'\xc0O\ \x00\xc0\xf9\xed\xd7_\xa6i\x9a\xf6\x16\xb3,\xe3\xea\xea\x8a8\x8eY,\x16X\xd6\ \xdf\xe3\x1c\xc7\x91\xba\xae\xa9\xaa\x8a\xa7\xa7\'6\x9b\xcd!@\x92$\x07\x8b\ \xbe\xef\x9b\xe7\xe5\xe5%a\x18"\xa5\xc4\xb6\xdf\xd7\xb2\xe38\xd2\xf7=UU\xf1\ \xf8\xf8HUUx\x9eG\x9a\xa6\x87\x00\xc76\xa8\xeb\x9a\xae\xeb\xf0}\x9f\xeb\xebk\ \xc20$MS\\\xd7}\x17\x80R\x8a\xddnG]\xd7\x94e\xc9\xd3\xd3\x13\xe38\x1e\xfd\ \xed\x1e\x80\x94\x12\xdf\xf7\xd1Z3\x0c\x03M\xd3\xb0^\xaf\x11B\xe0\xba.q\x1c#\ \xa5\xc4q\x8er3\x0c\x03}\xdfS\xd75_\xbf~e\xbd^\xd34\r\x8e\xe3\xe0\xfb>\xb6m\ \xd3\xb6-]\xd7\x1d\x07\x08\xc3\x90\x8b\x8b\x0b\x94R4MC\xd7u\xacV+\xba\xae\ \xc3q\x1c\x84\x10\xa4iz\x12`\x1cG\xca\xb2\xe4\xf9\xf9\x99\xdb\xdb[\xee\xef\ \xef\rx\x10\x04x\x9e\xc7f\xb39\r\x90$\t\x1f?~\xa4\xaek6\x9b\rEQ\xd0u\x1d\xbb\ \xdd\x8e\xbb\xbb;\xc6qd\x9a\xa6\x83L\xcc\x91\x17E\xc1z\xbdf\xbd^\xb3\xdb\xed\ \xd0Z\x1b\x80,\xcb\x88\xa2\x08\xa5\x14///\xc7\x01\xd24\xe5\xd3\xa7O\xbc\xbc\ \xbc\xd0\xf7=sw\xf4}\xcf\xed\xed-M\xd3`Y\x16B\x08\x92$\xd9\x03\x98k\xbdZ\xad\ x||\xc4\xb2,\xa2("\x0cC\x92$\xe1\xc3\x87\x0fdY\xb6\xe7\xfc\x00\xc0\xf3<\xe28\ 6N]\xd7\xc5\xb2,^__)\xcb\x92\xedv\xcb\xfd\xfd=Zk\xa6ib\x18\x06\x00\xaa\xaa2\ \x91o\xb7[\xfa\xbe\'\x8a"\x13\xf9\xe5\xe5%Y\x96\x99\xcc\x9d\x04\xf8\xb6\x14R\ J\xa4\x94\x0c\xc3\x80\xd6\xdaD\xfa\xf9\xf3g\x9a\xa6A\x08\xc1\xf9\xf99\x00y\ \x9e\xb3Z\xadx~~F\x08A\x14EDQD\x9a\xa6,\x97Knnn\xf0<\x8f\xef\xf5\xe6$\x80\ \xef\xfb\xf8\xbeO\xd34\xa6\x96\x00eYR\x96%y\x9e\xf3\xf0\xf0@Q\x14f=\xcfs\xba\ \xae\xdbK{\x92$\xa4ij\xfa\xbfi\x9a\xf7\x01\xcc&\xa5$I\x12\x93\xf2\xd9\x94R|\ \xf9\xf2\x05!\x04\x00\xd34\xa1\xb5&\x0cC\xe3<MS\xe28\xfeS\xed8\n0\x9f\xf6\ \xb9\xff\x83 `\x1cG\xe3\xb0(\n\xaa\xaa\xa2\xef{\x03\x1a\x86!q\x1c\x13\xc71Q\ \x14\xe1\xfb>\xae\xeb"\x84`\x18\x06\xf3\xdfw\x01h\xad\xe9\xfb\x9e\xae\xebPJa\ Y\x16q\x1cc\xdb\xb6\xc9\x84\x10\xe2(@\x9a\xa6\x04A\x80\x10\x02\xa5\x14]\xd7\ \xd1u\xdd\xc9L\xec\x01h\xad\x19\xc7\x11\xad5u]\x1b\xe7s4\xf3SJ\x89eY\xb4m\ \x0b\xbcu\xcf\xd9\xd9\x19gggDQ\x84\x94\x12\xa5\x14\xd34\xa1\x94\xa2\xaek\x82\ 0>N\x02\xccCd\x18\x06^__\xb1m\x9b0\x0c\xf1<\x0f\xd7u\x99\xa6\x89\xf3\xf3s\ \xf2<\x07\xde\x0e\x1f@\x14E,\x97K...L\xa4s\xf4\xf3\\\x98\xa6\t\xc7q\x0ef\xc2\ \x1e\xc0L\xab\xb5F)\x85\xeb\xba,\x16\x0b\x82 \xc0u]#<\x8e\xe3\xd0\xb6-\x9e\ \xe7\x01\x10\xc71WWWdY\x06\xbc\xb5\xabR\n\xdb\xb6)\x8a\x82\xb6mi\xdb\x16\xcb\ \xb2PJ\x9d\x06\x98ew\xb1X\x18\xfd\x0e\x82\xc0\xcc\x81\xd9\x82 `\xb9\\\x9a\ \xcd\xa4\x94&\xc5\xf0v>\x1c\xc7!\x08\x02\xa6i\xc2\xb6m\x94RF\xdaO\x02\xcc\ \x9a>\x0b\x89\xe7yx\x9ewp!\x99\xc1N\x99m\xdb\xe63\x7f\xdf\xedv\xf4}\xff\xc7%\ \xf0}\x9f4MM\xddOM\xbd\xbfb\xf3\x1eQ\x141\x8e\xa3)\xdbQ\x80yn\xcf\xa7\xfc[\ \xbd\xff\'fY\x96\xb9k|\x1f\xd4\xd130\xcf\xff\x7f\xd3\xc6q4w\x8c=\x80\xa6i\ \x8c\xb8\xe4yn.\x11\xff\x85)\xa5\xd8n\xb7\xd4um\xd6\xc4\xcfw\xc3\xff=\xc0\ \xefa\x89?u1\xd3\xf5 \x00\x00\x00\x00IEND\xaeB`\x82\xc4\x1f\x08\x9f' ) def getNoMailBitmap(): return wx.BitmapFromImage(getNoMailImage()) def getNoMailImage(): stream = cStringIO.StringIO(getNoMailData()) return wx.ImageFromStream(stream) def getNoMailIcon(): icon = wx.EmptyIcon() icon.CopyFromBitmap(getNoMailBitmap()) return icon #---------------------------------------------------------------------- def getErrMailData(): return zlib.decompress( 'x\xda\x01W\x05\xa8\xfa\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00 \x00\ \x00\x00 \x08\x06\x00\x00\x00szz\xf4\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\ \x08d\x88\x00\x00\x05\x0eIDATX\x85\xcd\x97\xcf\x8f\xdb\xd4\x16\xc7?v\xae\x7f\ \xc5N&\x8e\xd3L\x92\xceL%T\x15\rbQQ!\xe8\x0e\xc4\x92\xff\x80%H\xac\xdeC\xf0\ \xfe\x94\x07\xdb\xf7\x96\xac\xfa\x1f TT\t\x06\x90\xa0,*UB#\x90f:i"\'\x99L\ \xec\xd8\xf1\xaf\x98\xc5LLC\x92\x8aH\xa0r$/|t\xef9\x1f\xdf\xfb\xbd\xe7\\K\ \x92\\\xe2E\x9a\xfcB\xb3\x03b\xdb\t\x9f}\xfa\xdf\xfc\xf5\xd1\x88\x83\xcf?\ \xa7\xf2\xf81\x00\xde\xe1!\xa7\xef\xbd\xc7\xf7\xf5:\xff\xfa\xf7G\xd2\xdf\n\ \xb0w\xff>\xd7\x83\x80\xeah\x84q\xe5\x93F#:GG\xec\x95\xcb\xdb\x86C\xdaV\x03\ \xdfjj\xfeZ\x9e#\xc71\xf2|\x0e\xc0\\\x96\x99\xab*?J\x12oF\xf1V+\xb0\xb5\x06\ \x1cUE\xccfEr\x00y>G\xccf8\xaa\xbam8\xc4\x7f>\xf98\xcf\xf3|\xc9\xd9n\xb7\xd9\ \xdb\xdbCQ\x94%\xff\xf5\xef\xbe\xa3~\xef\x1e\\\\\xac\rV\xaf\xd7\xf9\xe6\xc3\ \x0f\xf3\xb37\xdeX\xf2\'I\xc2\x93\'Ox\xfa\xf4\xe9*@\xa5RYu\nA\x92$\xe8\xba\ \x8eeY\xc5cw\xbb\xe8\xba\xbe\xf1kt]g\x7f\x7f\x1f\xeb\xe5\x97\xf1}\xbfx\x82 @\ \x08A\xb5Z]\xcd\xb5.\x90\xe7y\x84a\xc8\xee\xee.\x86a`\x9a&\xedv\x1b\xab\xd1@\ <g\x99UU\xa5\xd1h\xa0\xb7\xdbt\xbb]...\x18\x8dF\xf4\xfb}\xd24];g\t`\x91L\x92\ .u\x94\xe79\xc3\xe1\x10UU)\x97\xcb\x94\xc2\x90r\x96\xb1I\xb6Y\x96\x11\x86!\ \xe3\xf1\x98\xc1`\xc0p8$\xcfsvvv\x8ax\xd3\xe9\x940\x0c\xd7\x03T\xabU:\x9d\ \x0e\xa5\xd2e\x8a\xf3\xf3s\xfa\xfd>I\x92\x000w]\xdaq\xcc\xa65\x88\xe3\x18\ \xd7uyrr\xc2\xc9\xc9\t\xa3\xd1\x88k\xd7\xae\xd1j\xb5\n\xc0n\xb7\xfb|\x80\xfd\ \xfd}\xd24%\x08\x02\xe28&\x08\x02\x92$\xa1\xd7\xeb\xa1\xb9.N\x1coH\xff;@\xaf\ \xd7#I\x12L\xd3\xc44M,\xcb\xa2\\.#\x84\xc0\xf7}\xfa\xfd\xfef\x80\xbd\xbd=&\ \x93\tQ\x14aY\x16\xaa\xaa2\x1e\x8fq]\x97\xb2\xeb\xf2\xd2\x9f\x00p]\x17\xc7q\ \xa8\xd5j\xa8\xaaJ\xa9T\xa2^\xafS\xadV9;;[\x9a\xb3\x04\xa0\xaa*\x96e!I\x12Q\ \x14\x15\xfb\x15\xc71\xbe\xef#\x84(\xf4\xb1\xce$IB\x08\x81\xa6i\x94\xcbe*\ \x95J\xa1\xabj\xb5Z|\xd0F\x80\x85U*\x15TUe0\x18\xd0\xeb\xf50M\x93N\xa7C\xb3\ \xd9D\xd3\xb4\x8d\x00\x9a\xa6\xd1l6\x99w:h\x9a\x86\x10\x02\xc7qh4\x1a\xa8\ \xaa\xca\x1f\xeb\xcdF\x00M\xd3\xd04\x8d\xe9t\x8a,\xcb\xc5\xbbh\xb7\x99\xbe\ \xf2\n%IB\xef\xf5P\xa6S\x00\x12\xd3d\xd6j1=<D\xb4\xdb\xc5y\x97e\x19\xc30\x8a\ \xf7g\xc5\xf7\\\x80M\x16\x1c\x1c\xd0{\xf7]f\xad\x16\xbb_|Q\x00D\x8d\x06\xee\ \xdbos~\xe7\x0e\xb3+\xc5\xffY\xdb\n \xb5m|\xdbF\xb9\xb8 ;:*\xfc\x99e1\xbdy\ \x13\xff\xf0p\xab\xe4\xf0O\xbd\x90DQD\x1c\xc7dY\x86a\x18\x08\xb1<Lq\x1c\xa2\ \x1b7\x98\\\x1d\xc9\xe8\xc6\r\x84\xe3`\x9a\xe6\xf28E!\xcb2<\xcf[Q\xffs\x01|\ \xdf\xc7u]\x84\x104\x9b\xcd\xa22.,\x06\xce\xb3\x8c\xe4\xaa\xa0(\xbb\xbbX\xb7\ o\xe3\x1c\x1c,\x8d\xcb\xb2\x8c\xe9t\x8a\xef\xfb4\x1a\x8d\x15\xc0\x15\x80$I\ \x08\x82\xa0xj\xb5\x1a\xb6m\xaft\xc0sE\xe1\xc20\x08\xaeDh\x9a&V\xa7\x83m\xdb\ K\xe3f\xb3\x19a\x18\x16\xf1$I*\xca\xfaZ\x80\xc9d\xc2\xe9\xe9)\x95J\x85V\xab\ \x85i\x9a+\xcb\x0f\x97M\xab\xd5j\x15\xc1\x14E\xc10\x8c\x95q\x8b:\xa0\xeb:\ \xb3\xd9\x8c\xd3\xd3S&\x93\xc9f\x80(\x8a\xf0<\x8fj\xb5\x8a\xe38+E\'MS\xd24E\ \nCjA\x80\xbchR\x8aB*\xcb\xcc\xae\x92.\xa0\x85\x10\xec\xec\xec\xa0\xeb:\xddn\ \x17\xcf\xf3\x88\xa2h3\xc0\xa2\x19\xd5j\xb5\x95}\x07\x08\x82\x80\xe1p\x88x\ \xfc\x18\xe7\xe8\x08\xa3\xdb\xbd\x04\xeft\x18\xdd\xbdKrx\x88\xe38+\x17\x8fE/\ \x90$\t\xd7u7\x03\x18\x86\x81m\xdbh\x9aV|\xed\xb36\x1d\x8d\x18\x1f\x1f\xa3}\ \xfd5;\xf7\xee!\xfd\xfc\xf3\xe5\xca\xdc\xba\x857\x9f3S\x14tIZ\xabxM\xd3\xb0m\ {e\xab\xd6j`\xd3\x91)=z\x84\xf3\xe5\x97\x94\x1f>D\x1b\x0c~\x0f>\x18p\xed\xfe\ }\x82\xf1\x98\xe0\x9dw\xf0^}u\xed\xfc8\x8eW5\x10\x86a\xd1$\xfa\xfd>\xaa\xaa\ \xae\x15\x1e@\xeb\xa7\x9fx\xe9\xc1\x03v\x8e\x8f\x91\x9fi\xcb\xcaxL\xed\xe1C$\ \xcf\xe3\x17\xc7\xa1\xf7\x87\xcb\xec\xc2\xd24\xa5\xdf\xef\x13\x04A\xe1\xdb\ \xfa\xbf\xe0\xab\x0f\xde\xcfo\x9e\x9da\xff\xf0\x03\xc6U\x1d\x08ww9\xbfs\x87\ \xe3\xeb\xd7y\xeb\x7f\xff\xff{\xff\x8c\x1e\xdd\xbe\x8dqp@\xe9\xd7_\xc9\xaf\ \x00\xbcz\x9d\xee\xdd\xbb<\xaa\xd7\xb7\r\xb7\xfd\n\xfc\xd5\xf6\xc2\x9b\xd1o\ \xd1r.\xaf\xfe\x90\x016\x00\x00\x00\x00IEND\xaeB`\x82\x8a\x1a\x9f\x99' ) def getErrMailBitmap(): return wx.BitmapFromImage(getErrMailImage()) def getErrMailImage(): stream = cStringIO.StringIO(getErrMailData()) return wx.ImageFromStream(stream) def getErrMailIcon(): icon = wx.EmptyIcon() icon.CopyFromBitmap(getErrMailBitmap()) return icon
doudz/checkfeedmail
icon.py
Python
bsd-2-clause
9,632
<?php namespace Entities; use KAGClient\Client as Client; /** * Description of Player * * @author William Schaller * @Entity @Table(name="sb_player") * @HasLifecycleCallbacks */ class Player { /** * * @var type * @Id @Column(type="integer") * @GeneratedValue */ protected $id; /** * * @var type * @Column(type="string", nullable=true) */ protected $name; /** * * @var type * @Column(type="datetime") */ protected $updateDate; /** * * @var type * @Column(type="datetime") */ protected $createDate; /** * * @var bool * @Column(type="boolean") */ protected $active = true; /** * * @var type * @Column(type="boolean") */ protected $banned = true; /** * * @var type * @Column(type="boolean") */ protected $gold = false; /** * * @var type * @Column(type="integer") */ protected $role = 0; /** * * @var type * @OneToOne(targetEntity="User", inversedBy="player") */ protected $user; /** * * @var \Doctrine\Common\Collections\ArrayCollection * @OneToMany(targetEntity="Buddy", mappedBy="player", orphanRemoval=true) */ protected $buddies; /** * * @var \Doctrine\Common\Collections\ArrayCollection * @OneToMany(targetEntity="PlayerServer", mappedBy="player", cascade={"persist"}, orphanRemoval=true) */ protected $servers; public function __construct() { $this->buddies = new \Doctrine\Common\Collections\ArrayCollection(); $this->servers = new \Doctrine\Common\Collections\ArrayCollection(); } public function getId() { return $this->id; } public function setId($value) { $this->id = $value; } public function getName() { return $this->name; } public function setName($value) { $this->name = $value; } public function getUpdateDate() { return $this->updateDate; } public function setUpdateDate($value) { $this->updateDate = $value; } /** * @PreUpdate */ public function preUpdateSetUpdateDate() { $this->updateDate = new \DateTime(); } public function getCreateDate() { return $this->createDate; } public function setCreateDate($value) { $this->createDate = $value; } /** * @PrePersist */ public function prePersistSetCreateDate() { $this->createDate = new \DateTime(); $this->updateDate = $this->createDate; } public function getActive() { return $this->active; } public function setActive($value) { $this->active = $value; } public function getBanned() { return $this->banned; } public function setBanned($value) { $this->banned = $value; } public function getGold() { return $this->gold; } public function setGold($value) { $this->gold = $value; } public function getRole() { return $this->role; } public function setRole($value) { $this->role = $value; } public function getUser() { return $this->user; } public function setUser($value) { if($this->user == $value) return; if($this->user instanceof User) $this->user->setPlayer(null); $this->user = $value; $this->user->setPlayer(this); } public function addBuddy($user) { if($this->buddyExists($user)) return; $new = new Buddy(); $new->setPlayer($this); $new->setUser($user); } /** * Only to be used if the buddy is being added from the other side * @param \Buddy $buddy */ public function addBuddyBuddy($buddy) { $this->buddies[] = $buddy; } public function buddyExists($user) { foreach($this->buddies as $buddy) { if($buddy->getUser() == $user) return true; } return false; } public function getBuddy($user) { foreach($this->buddies as $buddy) { if($buddy->getUser() == $user) return $buddy; } return null; } public function removeBuddy($user) { $buddy = $this->getBuddy($user); if($buddy == null) return; $this->buddies->removeElement($buddy); $buddy->removed($this); } public function removeBuddyBuddy(Buddy $buddy) { $this->buddies->removeElement($buddy); } public function getBuddies() { return $this->buddies; } public function addServer($server) { if($server instanceof Server) { $svr = new PlayerServer(); $svr->setPlayer($this); $svr->setServer($server); $this->servers[] = $svr; \ServerBrowser\EM::getInstance()->persist($svr); } else if ($server instanceof PlayerServer) { $this->servers[] = $server; } } public function updateFromAPI() { $cli = new Client(); $info = $cli->getPlayerInfo($this->getName()); if(isset($info['active'])) $this->setActive($info['active']); if(isset($info['banned'])) $this->setBanned($info['banned']); if(isset($info['gold'])) $this->setGold($info['gold']); if(isset($info['role'])) $this->setRole($info['role']); } } ?>
wschalle/kagsb
Model/Entities/Player.php
PHP
bsd-2-clause
5,073
cask "webex-meetings" do version "2111.1208.4112.2" sha256 :no_check if Hardware::CPU.intel? url "https://akamaicdn.webex.com/client/webexapp.dmg" else url "https://akamaicdn.webex.com/client/Cisco_Webex_Meetings.pkg" end name "Webex Meetings" desc "Video communication and virtual meeting platform" homepage "https://www.webex.com/" livecheck do url :url strategy :extract_plist end pkg "Cisco_Webex_Meetings.pkg" uninstall quit: [ "com.cisco.webexmeetingsapp", "com.cisco.webex.webexmta", ], delete: [ "/Applications/Cisco Webex Meetings.app", "/Applications/Webex", # App seems to get installed here on macOS < 10.15 "~/Library/Internet Plug-Ins/WebEx64.plugin", "~/Library/Application Support/WebEx Folder/atgpcext64.bundle", "~/Library/Application Support/WebEx Folder/Add-ons/Cisco WebEx Start.app", "~/Library/Application Support/WebEx Folder/T33_64UMC*/Meeting Center.app", "~/Library/Application Support/WebEx Folder/T33_64UMC*/WebexAppLauncher.app", ], launchctl: "com.webex.pluginagent", pkgutil: "mc.mac.webex.com", rmdir: "~/Library/Application Support/WebEx Folder/T33_64UMC*" zap trash: [ "~/Library/Application Support/WebEx Folder", "~/Library/Caches/com.cisco.webexmeetingsapp", "~/Library/Caches/com.cisco.webexmta", "~/Library/Caches/com.cisco.webex.Cisco-WebEx-Start", ] end
danielbayley/homebrew-cask
Casks/webex-meetings.rb
Ruby
bsd-2-clause
1,544
<?php include_once(dirname(__FILE__).'/../../vision.php'); include '../zahlavi.php'; panel(''.$jazyk['admin_264'].''); $id=$_GET['id']; $dotaz=mysql_query("SELECT * FROM prave_p where id='$id'"); while ($vypsat=mysql_fetch_assoc($dotaz)) { $smazane_poradi=$vypsat['poradi']; mysql_query("DELETE FROM prave_p WHERE id='$id'") or die (mysql_error()); mysql_query("UPDATE prave_p SET poradi = (poradi - 1) WHERE poradi > $smazane_poradi") or die (mysql_error()); echo "<p align='center'>".$jazyk['admin_265']."</p>"; echo "<p align='center'><a href='index.php'><span style='color: black;'>".$jazyk['admin_266']."</span></a></p>"; } include '../zapati.php'; ?>
NiCK-iProVision/iPV-CMS
admin/panely/delete2.php
PHP
bsd-2-clause
657
class Proselint < Formula include Language::Python::Virtualenv desc "Linter for prose" homepage "http://proselint.com" url "https://files.pythonhosted.org/packages/42/ff/8e7ad0108b8faffdf2ec7d170b4a8a3c9bc91f5077debf5381ef14702588/proselint-0.10.2.tar.gz" sha256 "3a87eb393056d1bc77d898e4bcf8998f50e9ad84f7b9ff7cf2720509ac8ef904" license "BSD-3-Clause" revision OS.mac? ? 3 : 4 head "https://github.com/amperser/proselint.git" livecheck do url :stable end bottle do cellar :any_skip_relocation sha256 "16677bb488b626f2a5ebab9c85b52e5aa34501861aaf146dd093fdeab9c8d7af" => :catalina sha256 "2cb69c3b259812c1eeb11cc83ec7fcd5d0e6a01485a784ecdb76c75e55a5ad18" => :mojave sha256 "51b225461669feb8926219f46de1fa4c438e875e9b6b9669f9191bd883679617" => :high_sierra sha256 "bd89e661ead0970e14a67aa149af02f9d647b5990e80e1a3e1d3df39ce078396" => :x86_64_linux end depends_on "python@3.8" resource "click" do url "https://files.pythonhosted.org/packages/95/d9/c3336b6b5711c3ab9d1d3a80f1a3e2afeb9d8c02a7166462f6cc96570897/click-6.7.tar.gz" sha256 "f15516df478d5a56180fbf80e68f206010e6d160fc39fa508b65e035fd75130b" end resource "future" do url "https://files.pythonhosted.org/packages/00/2b/8d082ddfed935f3608cc61140df6dcbf0edea1bc3ab52fb6c29ae3e81e85/future-0.16.0.tar.gz" sha256 "e39ced1ab767b5936646cedba8bcce582398233d6a627067d4c6a454c90cfedb" end resource "six" do url "https://files.pythonhosted.org/packages/16/d8/bc6316cf98419719bd59c91742194c111b6f2e85abac88e496adefaf7afe/six-1.11.0.tar.gz" sha256 "70e8a77beed4562e7f14fe23a786b54f6296e34344c23bc42f07b15018ff98e9" end def install virtualenv_install_with_resources end test do output = pipe_output("#{bin}/proselint --compact -", "John is very unique.") assert_match "Comparison of an uncomparable", output end end
maxim-belkin/homebrew-core
Formula/proselint.rb
Ruby
bsd-2-clause
1,874
package assertion_test import ( . "github.com/chai2010/gopkg/database/leveldb/internal/ginkgo" . "github.com/chai2010/gopkg/database/leveldb/internal/gomega" "testing" ) func TestAssertion(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Assertion Suite") }
chai2010/goleveldb
leveldb/internal/gomega/internal/assertion/assertion_suite_test.go
GO
bsd-2-clause
272
import flask; from flask import request import os import urllib.parse from voussoirkit import flasktools from voussoirkit import gentools from voussoirkit import stringtools import etiquette from .. import common site = common.site session_manager = common.session_manager # Individual albums ################################################################################ @site.route('/album/<album_id>') def get_album_html(album_id): album = common.P_album(album_id, response_type='html') response = common.render_template( request, 'album.html', album=album, view=request.args.get('view', 'grid'), ) return response @site.route('/album/<album_id>.json') def get_album_json(album_id): album = common.P_album(album_id, response_type='json') album = album.jsonify() return flasktools.json_response(album) @site.route('/album/<album_id>.zip') def get_album_zip(album_id): album = common.P_album(album_id, response_type='html') recursive = request.args.get('recursive', True) recursive = stringtools.truthystring(recursive) streamed_zip = etiquette.helpers.zip_album(album, recursive=recursive) if album.title: download_as = f'album {album.id} - {album.title}.zip' else: download_as = f'album {album.id}.zip' download_as = etiquette.helpers.remove_path_badchars(download_as) download_as = urllib.parse.quote(download_as) outgoing_headers = { 'Content-Type': 'application/octet-stream', 'Content-Disposition': f'attachment; filename*=UTF-8\'\'{download_as}', } return flask.Response(streamed_zip, headers=outgoing_headers) @site.route('/album/<album_id>/add_child', methods=['POST']) @flasktools.required_fields(['child_id'], forbid_whitespace=True) def post_album_add_child(album_id): album = common.P_album(album_id, response_type='json') child_ids = stringtools.comma_space_split(request.form['child_id']) children = list(common.P_albums(child_ids, response_type='json')) print(children) album.add_children(children, commit=True) response = album.jsonify() return flasktools.json_response(response) @site.route('/album/<album_id>/remove_child', methods=['POST']) @flasktools.required_fields(['child_id'], forbid_whitespace=True) def post_album_remove_child(album_id): album = common.P_album(album_id, response_type='json') child_ids = stringtools.comma_space_split(request.form['child_id']) children = list(common.P_albums(child_ids, response_type='json')) album.remove_children(children, commit=True) response = album.jsonify() return flasktools.json_response(response) @site.route('/album/<album_id>/remove_thumbnail_photo', methods=['POST']) def post_album_remove_thumbnail_photo(album_id): album = common.P_album(album_id, response_type='json') album.set_thumbnail_photo(None) common.P.commit(message='album remove thumbnail photo endpoint') return flasktools.json_response(album.jsonify()) @site.route('/album/<album_id>/refresh_directories', methods=['POST']) def post_album_refresh_directories(album_id): album = common.P_album(album_id, response_type='json') for directory in album.get_associated_directories(): if not directory.is_dir: continue digest = common.P.digest_directory(directory, new_photo_ratelimit=0.1) gentools.run(digest) common.P.commit(message='refresh album directories endpoint') return flasktools.json_response({}) @site.route('/album/<album_id>/set_thumbnail_photo', methods=['POST']) @flasktools.required_fields(['photo_id'], forbid_whitespace=True) def post_album_set_thumbnail_photo(album_id): album = common.P_album(album_id, response_type='json') photo = common.P_photo(request.form['photo_id'], response_type='json') album.set_thumbnail_photo(photo) common.P.commit(message='album set thumbnail photo endpoint') return flasktools.json_response(album.jsonify()) # Album photo operations ########################################################################### @site.route('/album/<album_id>/add_photo', methods=['POST']) @flasktools.required_fields(['photo_id'], forbid_whitespace=True) def post_album_add_photo(album_id): ''' Add a photo or photos to this album. ''' album = common.P_album(album_id, response_type='json') photo_ids = stringtools.comma_space_split(request.form['photo_id']) photos = list(common.P_photos(photo_ids, response_type='json')) album.add_photos(photos, commit=True) response = album.jsonify() return flasktools.json_response(response) @site.route('/album/<album_id>/remove_photo', methods=['POST']) @flasktools.required_fields(['photo_id'], forbid_whitespace=True) def post_album_remove_photo(album_id): ''' Remove a photo or photos from this album. ''' album = common.P_album(album_id, response_type='json') photo_ids = stringtools.comma_space_split(request.form['photo_id']) photos = list(common.P_photos(photo_ids, response_type='json')) album.remove_photos(photos, commit=True) response = album.jsonify() return flasktools.json_response(response) # Album tag operations ############################################################################# @site.route('/album/<album_id>/add_tag', methods=['POST']) def post_album_add_tag(album_id): ''' Apply a tag to every photo in the album. ''' response = {} album = common.P_album(album_id, response_type='json') tag = request.form['tagname'].strip() try: tag = common.P_tag(tag, response_type='json') except etiquette.exceptions.NoSuchTag as exc: response = exc.jsonify() return flasktools.json_response(response, status=404) recursive = request.form.get('recursive', False) recursive = stringtools.truthystring(recursive) album.add_tag_to_all(tag, nested_children=recursive, commit=True) response['action'] = 'add_tag' response['tagname'] = tag.name return flasktools.json_response(response) # Album metadata operations ######################################################################## @site.route('/album/<album_id>/edit', methods=['POST']) def post_album_edit(album_id): ''' Edit the title / description. ''' album = common.P_album(album_id, response_type='json') title = request.form.get('title', None) description = request.form.get('description', None) album.edit(title=title, description=description, commit=True) response = album.jsonify(minimal=True) return flasktools.json_response(response) @site.route('/album/<album_id>/show_in_folder', methods=['POST']) def post_album_show_in_folder(album_id): if not request.is_localhost: flask.abort(403) album = common.P_album(album_id, response_type='json') directories = album.get_associated_directories() if len(directories) != 1: flask.abort(400) directory = directories.pop() if os.name == 'nt': command = f'start explorer.exe "{directory.absolute_path}"' os.system(command) return flasktools.json_response({}) flask.abort(501) # Album listings ################################################################################### @site.route('/all_albums.json') @flasktools.cached_endpoint(max_age=15) def get_all_album_names(): all_albums = {album.id: album.display_name for album in common.P.get_albums()} response = {'albums': all_albums} return flasktools.json_response(response) def get_albums_core(): albums = list(common.P.get_root_albums()) albums.sort(key=lambda x: x.display_name.lower()) return albums @site.route('/albums') def get_albums_html(): albums = get_albums_core() response = common.render_template( request, 'album.html', albums=albums, view=request.args.get('view', 'grid'), ) return response @site.route('/albums.json') def get_albums_json(): albums = get_albums_core() albums = [album.jsonify(minimal=True) for album in albums] return flasktools.json_response(albums) # Album create and delete ########################################################################## @site.route('/albums/create_album', methods=['POST']) def post_albums_create(): title = request.form.get('title', None) description = request.form.get('description', None) parent_id = request.form.get('parent_id', None) if parent_id is not None: parent = common.P_album(parent_id, response_type='json') user = session_manager.get(request).user album = common.P.new_album(title=title, description=description, author=user) if parent_id is not None: parent.add_child(album) common.P.commit('create album endpoint') response = album.jsonify(minimal=False) return flasktools.json_response(response) @site.route('/album/<album_id>/delete', methods=['POST']) def post_album_delete(album_id): album = common.P_album(album_id, response_type='json') album.delete(commit=True) return flasktools.json_response({})
voussoir/etiquette
frontends/etiquette_flask/backend/endpoints/album_endpoints.py
Python
bsd-2-clause
9,106
#include <SFML-utils/gui/Configuration.hpp> #include <SFML-utils/gui/Widget.hpp> ///buttons #include <SFML-utils/gui/Button.hpp> #include <SFML-utils/gui/TextButton.hpp> #include <SFML-utils/gui/SpriteButton.hpp> //Containers #include <SFML-utils/gui/Container.hpp> #include <SFML-utils/gui/Frame.hpp> //layouts #include <SFML-utils/gui/Layout.hpp> #include <SFML-utils/gui/HLayout.hpp> #include <SFML-utils/gui/VLayout.hpp> namespace sfutils { using namespace gui; }
Krozark/SFML-book
extlibs/SFML-utils/include/SFML-utils/Gui.hpp
C++
bsd-2-clause
475
require "spec_helper" describe Rules::LittleFourWinds do subject { described_class } its(:score) { should == 64 } it "matches a standard hand with three pungs/kongs of winds and a pair of the fourth" do should match_hand ["W W W W", "S S S", "N N N", "2# 2# 2#", "E E"] should_not match_hand ["W W W W", "S S S", "N N N", "E E E", "2# 2#"] should_not match_hand ["W W W W", "S S S", "N N N", "E E"] end end
kajiki/mahjong-scoring
spec/rules/little_four_winds_spec.rb
Ruby
bsd-2-clause
431
<?php require_once(__DIR__ . '/../bootstrap.php'); require_once(__DIR__ . '/../include/checkAuth.php'); ?> <!DOCTYPE html> <html> <head> <?php require_once(__DIR__ . '/../include/header.php'); ?> </head> <body> <div class="container"> <?php require_once(__DIR__ . '/../include/top.php'); ?> <h1 class="page-header">查詢其他部落格公開資訊</h1> <h3>呼叫方式</h3> <pre>$pixapi->blog->info('userName');</pre> <h3><a href="#execute" name="execute">實際測試</a></h3> <form action="#execute" class="form-inline" role="form" method="POST"> <div class="form-group"> <label class="sr-only" for="query">使用者帳號</label> <input type="text" class="form-control" id="query" name="query" placeholder="請輸入使用者帳號"> </div> <button type="submit" class="btn btn-primary">查詢</button> </form> <?php $query = $_POST['query']; if ('' != $query) { ?> <h3>執行</h3> <pre>$pixapi->blog->info('<?= $query; ?>');</pre> <h3>執行結果</h3> <pre><?php print_r($pixapi->blog->info($query)); ?></pre> <?php } ?> </div> </body> </html>
pixnet/pixnet-php-sdk
examples/blog/other_info.php
PHP
bsd-2-clause
1,169
#!/usr/bin/ruby -w # # $Id$ require 'yaml' require 'getoptlong' require 'net/https' require 'uri' require 'pp' require 'socket' def usage script_name = File.basename( $0 ) puts %{ Usage: ruby #{script_name} --essid|-e ESSID --status|-s on|off [--debug|-d] } end response = loginuri = status = debug = username = password = essid = nil options = GetoptLong.new( [ "--essid", "-e", GetoptLong::REQUIRED_ARGUMENT ], [ "--status", "-s", GetoptLong::REQUIRED_ARGUMENT ], [ "--debug", "-d", GetoptLong::NO_ARGUMENT ] ) options.ordering = GetoptLong::PERMUTE begin options.each { |option, argument| case option when "--essid" essid = argument when "--debug" debug = true when "--status" status = argument end } rescue => err usage exit end if essid.nil? puts "Please provide essid." usage exit end # When logout, do nothing exit if status == "off" # Search username and password from ~/.wifispot.yam f = open(ENV['HOME'] + "/.wifispot.yam") strWifiSettings = f.read() f.close() yamlWifiSettings = YAML.load(strWifiSettings) username = URI.encode(yamlWifiSettings[essid]['login']) password = URI.encode(yamlWifiSettings[essid]['password']) # Try to access Google and get login url. retrycount = 0 while status && retrycount < 16 do begin Socket::getaddrinfo('vauth.lw.livedoor.com', 'www') break rescue => err retrycount += 1 end end p 'Failed to resolve address.' if debug && retrycount >= 16 retrycount = 0 while retrycount < 16 do response = Net::HTTP.get_response(URI.parse('http://www.google.com/')) if response.code == "302" loginurl = URI.parse('https://vauth.lw.livedoor.com/auth/index?sn=009&name='+username+'&password='+password+'&original_url=http://www.google.com/') p loginurl.path if debug p loginurl.query if debug https = Net::HTTP.new(loginurl.host, loginurl.port) https.use_ssl = true https.verify_mode = OpenSSL::SSL::VERIFY_PEER https.verify_depth = 5 https.start { response = https.post(loginurl.path, loginurl.query) } p response.code if debug p response.body if debug elsif response.code == "200" break else p response.code if debug end retrycount += 1 end
hiroaki0404/WifiLauncher
src/livedoorweb.rb
Ruby
bsd-2-clause
2,301
#!/usr/bin/env python import sys def ip2str(ip): l = [ (ip >> (3*8)) & 0xFF, (ip >> (2*8)) & 0xFF, (ip >> (1*8)) & 0xFF, (ip >> (0*8)) & 0xFF, ] return '.'.join([str(i) for i in l]) def str2ip(line): a, b, c, d = [int(s) for s in line.split('.')] ip = 0 ip += (a << (3*8)) ip += (b << (2*8)) ip += (c << (1*8)) ip += (d << (0*8)) return ip blockip = str2ip(sys.stdin.readline()) hostmask = 1 bitcount = 1 for line in sys.stdin.readlines(): try: ip = str2ip(line.strip()) except: print 'Ignored line:', line, continue while (blockip & (~hostmask)) != (ip & (~hostmask)): hostmask = (hostmask << 1) | 1 bitcount += 1 print ip2str(blockip & (~hostmask)) + '/' + str(bitcount), 'hostmask =', ip2str(hostmask) print 'wrong way around'
owalch/oliver
linux/config/scripts/ipblock.py
Python
bsd-2-clause
870
package com.blazeloader.api.recipe; import com.google.common.collect.Lists; import net.minecraft.block.Block; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; import net.minecraft.world.World; import java.util.*; public class ApiCrafting { private static final Map<Integer, BLCraftingManager> instances = new HashMap<Integer, BLCraftingManager>(); private static int nextId = 1; static { instances.put(0, new BLCraftingManager(0, CraftingManager.getInstance().getRecipeList())); } /** * Gets a wrapped instance of the normal CraftingManager. * @return Manager instance of CraftingManager */ public static BLCraftingManager getVanillaCraftingManager() { return instances.get(0); } /** * Intended for compatibility with mods that implemement their * own CraftingManageers based off of the vanilla one. * * Will parse a vanilla minecraft CraftingManager to a Blazeloader apis compatible Manager. * * It is not recommened to use this method often. Rather start off with a Manager * or keep a reference to the converted result for later use. * * @param manager CraftingManager to convert * * @return Manager corresponding to the given CraftingManager */ public static BLCraftingManager toManager(CraftingManager manager) { for (BLCraftingManager i : instances.values()) { if (i.equals(manager)) return i; } return createCraftingManager((ArrayList<IRecipe>)manager.getRecipeList()); } /** * Gets a CraftingManager from the pool by it's unique id. * * @param id integer id of the manager you'd like to find. * * @return Manager or null if not found. */ public static BLCraftingManager getManagerFromId(int id) { return instances.containsKey(id) ? instances.get(id) : null; } /** * Creates a brand spanking **new** Crafting Manager. */ public static BLCraftingManager createCraftingManager() { return createCraftingManager(new ArrayList<IRecipe>()); } private static BLCraftingManager createCraftingManager(ArrayList<IRecipe> startingRecipes) { int id = nextId++; instances.put(id, new BLCraftingManager(id, startingRecipes)); return instances.get(id); } /** * Custom implementation of the CraftingManager. * Supports additional functionality such as reverse crafting, * crafting areas greater than 3x3 and methods for removing recipes. * */ public static final class BLCraftingManager implements Comparable<BLCraftingManager> { private final int id; private final List<IRecipe> recipes; private BLCraftingManager(int n, List<IRecipe> recipes) { id = n; this.recipes = recipes; } /** * Gets the unique integer id for this CraftingManager. * Can be used to retrieve this manager again from the pool of CraftingManagers. * * @return integer id */ public int getId() { return id; } /** * Returns an unmodifieable list of recipes registered to this CraftingManager. * * @return List of Recipes */ public List<IRecipe> getRecipeList() { return Collections.unmodifiableList(recipes); } /** * Adds a shaped recipe to this CraftingManager. * * @param output ItemStack output for this recipe * @param input Strings of recipe pattern followed by chars mapped to Items/Blocks/ItemStacks */ public ShapedRecipe addRecipe(ItemStack output, Object... input) { ShapedRecipe result = createShaped(output, false, input); recipes.add(result); return result; } /** * Adds a shapeless crafting recipe to this CraftingManager. * * @param output ItemStack output for this recipe * @param input An array of ItemStack's Item's and Block's that make up the recipe. */ public ShapelessRecipe addShapelessRecipe(ItemStack output, Object... input) { ShapelessRecipe result = createShapeless(output, false, input); recipes.add(result); return result; } /** * Adds a shaped recipe to this CraftingManager. * * @param output ItemStack output for this recipe * @param input Strings of recipe pattern followed by chars mapped to Items/Blocks/ItemStacks */ public ReversibleShapedRecipe addReverseRecipe(ItemStack output, Object... input) { ShapedRecipe result = createShaped(output, true, input); recipes.add(result); return (ReversibleShapedRecipe)result; } /** * Adds a shapeless crafting recipe to this CraftingManager. * * @param output ItemStack output for this recipe * @param input An array of ItemStack's Item's and Block's that make up the recipe. */ public ReversibleShapelessRecipe addReverseShapelessRecipe(ItemStack output, Object... input) { ShapelessRecipe result = createShapeless(output, true, input); recipes.add(result); return (ReversibleShapelessRecipe)result; } /** * Adds an IRecipe to this RecipeManager. * * @param recipe A recipe that will be added to the recipe list. */ public void addRecipe(ShapelessRecipe recipe) { recipes.add(recipe); } /** * Adds an IRecipe to this RecipeManager. * * @param recipe A recipe that will be added to the recipe list. */ public void addRecipe(ShapedRecipe recipe) { recipes.add(recipe); } /** * Adds an IRecipe to this RecipeManager. * * @param recipe A recipe that will be added to the recipe list. */ public void addRecipe(IReversibleRecipe recipe) { recipes.add(recipe); } /** * Removes the given recipe * * @param recipe recipe to be removed * * @return true if the recipe was removed, false otherwise */ public boolean removeRecipe(IRecipe recipe) { int index = recipes.indexOf(recipe); if (index >= 0) { recipes.remove(index); return true; } return false; } /** * Removes recipes for the given item * * @param result ItemStack result of the recipe to be removed * * @return total number of successful removals */ public int removeRecipe(ItemStack result) { return removeRecipe(result, -1); } /** * Removes recipes for the given item * * @param result ItemStack result of the recipe to be removed * @param maxRemovals Maximum number of removals * * @return total number of successful removals */ public int removeRecipe(ItemStack result, int maxRemovals) { int count = 0; for (int i = 0; i < recipes.size(); i++) { if (recipes.get(i).getRecipeOutput() == result) { count++; recipes.remove(i); if (maxRemovals > 0 && count >= maxRemovals) return count; } } return count; } private ShapedRecipe createShaped(ItemStack output, boolean reverse, Object... input) { String recipe = ""; int index = 0; int width = 0; int height = 0; if (input[index] instanceof String[]) { for (String i : (String[])input[index++]) { ++height; width = i.length(); recipe += i; } } else { while (input[index] instanceof String) { String line = (String)input[index++]; ++height; width = line.length(); recipe += line; } } HashMap<Character, ItemStack> stackmap = new HashMap<Character, ItemStack>(); while (index < input.length) { char var13 = (Character) input[index]; ItemStack var15 = null; if (input[index + 1] instanceof Item) { var15 = new ItemStack((Item)input[index + 1]); } else if (input[index + 1] instanceof Block) { var15 = new ItemStack((Block)input[index + 1], 1, 32767); } else if (input[index + 1] instanceof ItemStack) { var15 = (ItemStack)input[index + 1]; } stackmap.put(var13, var15); index += 2; } ItemStack[] stacks = new ItemStack[width * height]; for (int i = 0; i < width * height; i++) { char key = recipe.charAt(i); if (stackmap.containsKey(key)) { stacks[i] = stackmap.get(key).copy(); } else { stacks[i] = null; } } if (reverse) return new ReversibleShapedRecipe(width, height, stacks, output); return new ShapedRecipe(width, height, stacks, output); } private ShapelessRecipe createShapeless(ItemStack output, boolean reverse, Object ... input) { ArrayList itemStacks = Lists.newArrayList(); for (Object obj : input) { if (obj instanceof ItemStack) { itemStacks.add(((ItemStack) obj).copy()); } else if (obj instanceof Item) { itemStacks.add(new ItemStack((Item) obj)); } else { if (!(obj instanceof Block)) throw new IllegalArgumentException("Invalid shapeless recipe: unknown type " + obj.getClass().getName() + "!"); itemStacks.add(new ItemStack((Block) obj)); } } if (reverse) return new ReversibleShapelessRecipe(output, itemStacks); return new ShapelessRecipe(output, itemStacks); } /** * Retrieves the result of a matched recipe in this RecipeManager. * * @param inventory inventory containing the crafting materials * @param world the world that the crafting is being done in (usually the world of the player) * * @return ItemStack result or null if none match */ public ItemStack findMatchingRecipe(InventoryCrafting inventory, World world) { for (IRecipe i : recipes) { if (i.matches(inventory, world)) return i.getCraftingResult(inventory); } return null; } /** * Retrieves the input required to craft the given item. * * @param recipeOutput ItemStack you wish to uncraft * @param width width of crafting table * @param height height of crafting table * * @return ItemStack[] array of inventory contents needed */ public ItemStack[] findRecipeInput(ItemStack recipeOutput, int width, int height) { for (IRecipe i : recipes) { if (i instanceof IReversibleRecipe) { IReversibleRecipe recipe = ((IReversibleRecipe)i); if (recipe.matchReverse(recipeOutput, width, height)) return recipe.getRecipeInput(); } } return null; } /** * Gets the remaining contents for the inventory after performing a craft. * * @param inventory inventory containing the crafting materials * @param world the world that the crafting is being done in (usually the world of the player) * * @return ItemStack[] array or remaining items */ public ItemStack[] getUnmatchedInventory(InventoryCrafting inventory, World world) { for (IRecipe i : recipes) { if (i.matches(inventory, world)) return i.getRemainingItems(inventory); } ItemStack[] newInventory = new ItemStack[inventory.getSizeInventory()]; for (int i = 0; i < newInventory.length; i++) { newInventory[i] = inventory.getStackInSlot(i); } return newInventory; } public boolean equals(Object obj) { if (obj instanceof BLCraftingManager) { return ((BLCraftingManager) obj).id == id; } if (obj instanceof CraftingManager) { return recipes.equals(((CraftingManager)obj).getRecipeList()); } if (obj instanceof List<?>) { return obj.equals(recipes); } return super.equals(obj); } public int compareTo(BLCraftingManager o) { return o.id - id; } } }
warriordog/BlazeLoader
src/com/blazeloader/api/recipe/ApiCrafting.java
Java
bsd-2-clause
12,203
cask 'dashlane' do version '6.1942.0.24426' sha256 'c5b37fe0c36d42014a8fde4ce4334833fbf5d6815b37cc2df732dd90a6aaae24' # d3mfqat9ni8wb5.cloudfront.net/releases was verified as official when first introduced to the cask url "https://d3mfqat9ni8wb5.cloudfront.net/releases/#{version.major_minor_patch}/#{version}/release/Dashlane.dmg" appcast 'https://ws1.dashlane.com/5/binaries/query?format=json&os=OS_X_10_14_5&target=archive&platform=launcher_macosx' name 'Dashlane' homepage 'https://www.dashlane.com/' depends_on macos: '>= :sierra' app 'Dashlane.app' end
jasmas/homebrew-cask
Casks/dashlane.rb
Ruby
bsd-2-clause
580
""" Workaround for a conda-build bug where failing to compile some Python files results in a build failure. See https://github.com/conda/conda-build/issues/1001 """ import os import sys py2_only_files = [] py3_only_files = [ 'numba/tests/annotation_usecases.py', ] def remove_files(basedir): """ Remove unwanted files from the current source tree """ if sys.version_info >= (3,): removelist = py2_only_files msg = "Python 2-only file" else: removelist = py3_only_files msg = "Python 3-only file" for relpath in removelist: path = os.path.join(basedir, relpath) print("Removing %s %r" % (msg, relpath)) os.remove(path) if __name__ == "__main__": remove_files('.')
stefanseefeld/numba
buildscripts/remove_unwanted_files.py
Python
bsd-2-clause
764
#include "clwrapper.h" #include <cstdio> #include <iostream> #define PLATFORM 0 #define DEVICE 0 #define GROUPSIZE 4 int main(int argc, char **argv) { // platform/device info std::cout << clinfo() << std::endl; // thread0 runs outer xyvals[0] times // inner xyvals[1] times // other threads do opposite int xyvals[2]; if (argc == 3) { xyvals[0] = atoi(argv[1]); xyvals[1] = atoi(argv[2]); } else { xyvals[0] = 4; xyvals[1] = 1; } // trace shared array A[] after each barrier, for each thread // number of trace items := // 8 values in A[] // __syncthreads() hit (xyvals[0]*xyvals[1]) times // by GROUPSIZE threads int ntrace = 8 * (xyvals[0]*xyvals[1]) * GROUPSIZE; int *trace = new int[ntrace]; for (int i=0; i<ntrace; i++) { trace[i] = 99; } // also record the final state of A int final[8]; for (int i=0; i<8; i++) { final[i] = 99; } // creates a context and command queue CLWrapper clw(PLATFORM, DEVICE, /*profiling=*/false); // compile the OpenCL code const char *filename = "nested.cl"; cl_program program = clw.compile(filename); // generate all kernels clw.create_all_kernels(program); // get handlers to kernels cl_kernel k = clw.kernel_of_name("k"); // create some memory objects on the device cl_mem d_xyvals = clw.dev_malloc(sizeof(int)*2, CL_MEM_READ_ONLY); cl_mem d_trace = clw.dev_malloc(sizeof(int)*ntrace, CL_MEM_READ_WRITE); cl_mem d_final = clw.dev_malloc(sizeof(int)*8, CL_MEM_READ_WRITE); // memcpy into these objects clw.memcpy_to_dev(d_xyvals, sizeof(int)*2, xyvals); clw.memcpy_to_dev(d_trace, sizeof(int)*ntrace, trace); clw.memcpy_to_dev(d_final, sizeof(int)*8, final); // set kernel arguments clw.kernel_arg(k, d_xyvals, d_trace, d_final); // run the kernel cl_uint dim = 1; size_t global_work_size = GROUPSIZE; size_t local_work_size = GROUPSIZE; clw.run_kernel(k, dim, &global_work_size, &local_work_size); // memcpy back trace clw.memcpy_from_dev(d_trace, sizeof(int)*ntrace, trace); // printout trace int stride = 8 * (xyvals[0]*xyvals[1]); for (int lid=0; lid<GROUPSIZE; lid++) { printf("lid = %d\n", lid); for (int xy=0; xy<(xyvals[0]*xyvals[1]); xy++) { printf("(%d) A = {{%d,%d,%d,%d}, {%d,%d,%d,%d}}\n", xy, trace[(lid*stride)+(xy*8)+0], trace[(lid*stride)+(xy*8)+1], trace[(lid*stride)+(xy*8)+2], trace[(lid*stride)+(xy*8)+3], trace[(lid*stride)+(xy*8)+4], trace[(lid*stride)+(xy*8)+5], trace[(lid*stride)+(xy*8)+6], trace[(lid*stride)+(xy*8)+7] ); } printf("---\n"); } // print out final state clw.memcpy_from_dev(d_final, sizeof(int)*8, final); printf("final state\n"); printf(" A = {{%d,%d,%d,%d}, {%d,%d,%d,%d}}\n", final[0],final[1],final[2],final[3], final[4],final[5],final[6],final[7]); // clean up delete[] trace; return 0; }
nchong/litmus
tests/nested/cl/nested.cpp
C++
bsd-2-clause
2,955
/** * Copyright (c) 2007-2012, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 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. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef _top_status_source_hh #define _top_status_source_hh #include <string> #include "lnav_config.hh" #include "logfile_sub_source.hh" #include "statusview_curses.hh" class top_status_source : public status_data_source { public: typedef listview_curses::action::mem_functor_t< top_status_source> lv_functor_t; typedef enum { TSF_TIME, TSF_PARTITION_NAME, TSF_VIEW_NAME, TSF_STITCH_VIEW_FORMAT, TSF_FORMAT, TSF_STITCH_FORMAT_FILENAME, TSF_FILENAME, TSF__MAX } field_t; top_status_source() : filename_wire(*this, &top_status_source::update_filename), view_name_wire(*this, &top_status_source::update_view_name) { this->tss_fields[TSF_TIME].set_width(28); this->tss_fields[TSF_PARTITION_NAME].set_width(34); this->tss_fields[TSF_PARTITION_NAME].set_left_pad(1); this->tss_fields[TSF_VIEW_NAME].set_width(8); this->tss_fields[TSF_VIEW_NAME].set_role(view_colors::VCR_STATUS_TITLE); this->tss_fields[TSF_VIEW_NAME].right_justify(true); this->tss_fields[TSF_STITCH_VIEW_FORMAT].set_width(2); this->tss_fields[TSF_STITCH_VIEW_FORMAT].set_stitch_value( view_colors::VCR_STATUS_STITCH_SUB_TO_TITLE, view_colors::VCR_STATUS_STITCH_TITLE_TO_SUB); this->tss_fields[TSF_STITCH_VIEW_FORMAT].right_justify(true); this->tss_fields[TSF_FORMAT].set_width(20); this->tss_fields[TSF_FORMAT].set_role(view_colors::VCR_STATUS_SUBTITLE); this->tss_fields[TSF_FORMAT].right_justify(true); this->tss_fields[TSF_STITCH_FORMAT_FILENAME].set_width(2); this->tss_fields[TSF_STITCH_FORMAT_FILENAME].set_stitch_value( view_colors::VCR_STATUS_STITCH_NORMAL_TO_SUB, view_colors::VCR_STATUS_STITCH_SUB_TO_NORMAL); this->tss_fields[TSF_STITCH_FORMAT_FILENAME].right_justify(true); this->tss_fields[TSF_FILENAME].set_min_width(35); /* XXX */ this->tss_fields[TSF_FILENAME].set_share(1); this->tss_fields[TSF_FILENAME].right_justify(true); }; lv_functor_t filename_wire; lv_functor_t view_name_wire; size_t statusview_fields(void) { return TSF__MAX; }; status_field &statusview_value_for_field(int field) { return this->tss_fields[field]; }; void update_time(const struct timeval &current_time) { status_field &sf = this->tss_fields[TSF_TIME]; char buffer[32]; buffer[0] = ' '; strftime(&buffer[1], sizeof(buffer) - 1, lnav_config.lc_ui_clock_format.c_str(), localtime(&current_time.tv_sec)); sf.set_value(buffer); }; void update_time() { struct timeval tv; gettimeofday(&tv, nullptr); this->update_time(tv); }; void update_filename(listview_curses *lc) { status_field & sf_partition = this->tss_fields[TSF_PARTITION_NAME]; status_field & sf_format = this->tss_fields[TSF_FORMAT]; status_field & sf_filename = this->tss_fields[TSF_FILENAME]; struct line_range lr(0); if (lc->get_inner_height() > 0) { string_attrs_t::const_iterator line_attr; std::vector<attr_line_t> rows(1); lc->get_data_source()-> listview_value_for_rows(*lc, lc->get_top(), rows); string_attrs_t &sa = rows[0].get_attrs(); line_attr = find_string_attr(sa, &logline::L_FILE); if (line_attr != sa.end()) { logfile *lf = (logfile *)line_attr->sa_value.sav_ptr; if (lf->get_format()) { sf_format.set_value("% 13s", lf->get_format()->get_name().get()); } else if (!lf->get_filename().empty()) { sf_format.set_value("% 13s", "plain text"); } else{ sf_format.clear(); } if (sf_filename.get_width() > (ssize_t) lf->get_filename().length()) { sf_filename.set_value(lf->get_filename()); } else { sf_filename.set_value(lf->get_unique_path()); } } else { sf_format.clear(); sf_filename.clear(); } line_attr = find_string_attr(sa, &logline::L_PARTITION); if (line_attr != sa.end()) { auto bm = (bookmark_metadata *)line_attr->sa_value.sav_ptr; sf_partition.set_value(bm->bm_name.c_str()); } else { sf_partition.clear(); } } else { sf_format.clear(); if (lc->get_data_source() != NULL) { sf_filename.set_value(lc->get_data_source()->listview_source_name(*lc)); } } }; void update_view_name(listview_curses *lc) { status_field &sf_view_name = this->tss_fields[TSF_VIEW_NAME]; sf_view_name.set_value("%s ", lc->get_title().c_str()); }; private: status_field tss_fields[TSF__MAX]; }; #endif
sureshsundriyal/lnav
src/top_status_source.hh
C++
bsd-2-clause
6,788
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import random import sys class DayLife: """Life in a day.""" def __init__(self, date, life): """Set birth datetime and life.""" self.birthdate = date self.life = life finalyear = self.birthdate.year + self.life finaldate = datetime.datetime(finalyear, self.birthdate.month, self.birthdate.day) self.finaldate = finaldate - datetime.timedelta(days=1) def now(self): """Calculate current time.""" curdate = datetime.datetime.now() maxdays = (self.finaldate - self.birthdate).days curdays = (curdate - self.birthdate).days curtime = datetime.timedelta(days=1) / maxdays curtime = curtime * curdays return datetime.time( (curtime.seconds / 60) / 60, (curtime.seconds / 60) % 60, curtime.seconds % 60) if __name__ == '__main__': # options startyear = 1900 endyear = 2000 life = 200 print startyear, "<= a <=", endyear print "n =", life daycount = (datetime.datetime(endyear, 12, 31) - datetime.datetime(startyear, 1, 1)).days birthdate = datetime.datetime(startyear, 1, 1) + \ datetime.timedelta(days=random.randint(0, daycount)) args = sys.argv if len(args) == 4: year = int(args[1]) month = int(args[2]) date = int(args[3]) birthdate = datetime.datetime(year, month, date) print "birthdate:", birthdate.date() mylife = DayLife(birthdate, life) print "finaldate:", mylife.finaldate.date() print "today:", mylife.now()
wakamori/GoForIt
1/1-2.py
Python
bsd-2-clause
1,719
#include <vector> #include <iostream> #include <SDL/SDL.h> #include <SDL/SDL_gfxPrimitives.h> #include <SDL/SDL_image.h> #include <SDL/SDL_mixer.h> #include "base.h" #include "game.h" #include "video.h" void draw3DLine( SDL_Surface *video, Vec3 &camera, Vec3 &p0, Vec3 &p1, int r, int g, int b ) { float x0 = ( XRES / 2 ) + ( ( p0.x - camera.x ) / ( p0.z - camera.z ) ); float y0 = ( YRES / 2 ) - ( ( p0.y - camera.y ) / ( p0.z - camera.z ) ); float x1 = ( XRES / 2 ) + ( ( p1.x - camera.x ) / ( p1.z - camera.z ) ); float y1 = ( YRES / 2 ) - ( ( p1.y - camera.y ) / ( p1.z - camera.z ) ); lineRGBA( video, x0, y0, x1, y1, r, g, b, 255 ); lineRGBA( video, 100 + p0.x / 10, 100 - p0.z * 10, 100 + p1.x / 10, 100 - p1.z * 10, r, g, b, 255 ); } void drawXZPlane( SDL_Surface *video, Vec3 &camera, Vec3 &p0, Vec3 &p1, int r, int g, int b ) { Vec3 _p0; Vec3 _p1; Vec3 _p2; Vec3 _p3; _p0.set( p0 ); _p1.set( p1 ); _p0.y = p0.y + ( ( p1.y - p0.y ) / 2.0f ); _p1.y = _p0.y; _p2.y = _p0.y; _p3.y = _p0.y; _p1.set( p1.x, _p0.y, p0.z ); _p2.set( p1.x, _p0.y, p1.z ); _p3.set( p0.x, _p0.y, p1.z ); draw3DLine( video, camera, _p0, _p1, r, g, b ); draw3DLine( video, camera, _p2, _p1, r, g, b ); draw3DLine( video, camera, _p2, _p3, r, g, b ); draw3DLine( video, camera, _p0, _p3, r, g, b ); } void drawCube( SDL_Surface *video, Vec3 &camera, Vec3 &p0, Vec3 &p1, int r, int g, int b ) { Vec3 _p0( p0 ); Vec3 _p1( p1 ); _p1.y = p0.y; drawXZPlane( video, camera, _p0, _p1, r, g, b ); _p1.y = p1.y; _p0.y = p1.y; drawXZPlane( video, camera, _p0, _p1, r, g, b ); _p0.set( p0 ); _p1.set( p0 ); _p1.y = p1.y; draw3DLine( video, camera, _p0, _p1, r, g, b ); _p0.set( p1 ); _p1.set( p1 ); _p1.y = p0.y; draw3DLine( video, camera, _p0, _p1, r, g, b ); _p0.set( p1 ); _p1.set( p1 ); _p1.y = p0.y; _p0.z = p0.z; _p1.z = p0.z; draw3DLine( video, camera, _p0, _p1, r, g, b ); _p0.set( p0 ); _p1.set( p0 ); _p1.y = p1.y; _p0.z = p1.z; _p1.z = p1.z; draw3DLine( video, camera, _p0, _p1, r, g, b ); } void refreshScreen( SDL_Surface *video, Level &level ) { Plane *plane; SDL_Rect rect; Uint32 colour; Vec3 p0; Vec3 p1; rect.x = 0; rect.y = 0; rect.w = XRES; rect.h = YRES; colour = SDL_MapRGB( video->format, 0, 0, 0 ); SDL_FillRect( video, &rect, colour ); rect.x = 0; rect.y = YRES - 40; rect.w = ( XRES / DEFAULTJUMPS ) * level.jumps; rect.h = 20; colour = SDL_MapRGB( video->format, 255, 255, 255 ); SDL_FillRect( video, &rect, colour ); rect.x = 0; rect.y = YRES - 20; rect.w = ( XRES / DEFAULTTIME ) * level.timeLeft; rect.h = 20; colour = SDL_MapRGB( video->format, 128, 128, 128 ); SDL_FillRect( video, &rect, colour ); plane = level.planes[ level.nextId ]; rect.x = XRES - 50; rect.y = 0; rect.w = 50; rect.h = 50; colour = SDL_MapRGB( video->format, plane->r, plane->g, plane->b ); SDL_FillRect( video, &rect, colour ); p0.set( -600, 0, 1 ); p1.set( 600, 0, 10 ); drawXZPlane( video, level.camera, p0, p1, 0, 255, 0 ); for ( int c = 0; c < level.planes.size(); ++c ) { plane = level.planes[ c ]; drawXZPlane( video, level.camera, plane->p0, plane->p1, plane->r, plane->g, plane->b ); } Particle *p; for ( int c = 0; c < level.player.jetpack.particles.size(); ++c ) { p = level.player.jetpack.particles[ c ]; draw3DLine( video, level.camera, p->position, p->position, 255 - p->size, 0, 0 ); } p0.set( level.player.bodyRep.position.x - 20, level.player.bodyRep.position.y, level.player.bodyRep.position.z ); p1.set( level.player.bodyRep.position.x + 20, level.player.bodyRep.position.y + 100, level.player.bodyRep.position.z + 0.1f ); drawCube( video, level.camera, p0, p1, 0, 0, 255 ); SDL_UpdateRect( video, 0, 0, 0, 0 ); } void showScreen( SDL_Surface *video, SDL_Surface *screen ) { SDL_Event event; SDL_BlitSurface( screen, NULL, video, NULL ); SDL_Flip( video ); while ( true ) { if ( SDL_PollEvent( &event ) ) { if ( event.type == SDL_KEYDOWN ) { return; } } } }
TheFakeMontyOnTheRun/island-domination
video.cpp
C++
bsd-2-clause
4,922
package com.rhcloud.igorbotian.rsskit.rest; import com.fasterxml.jackson.databind.JsonNode; import org.apache.http.NameValuePair; import java.io.IOException; import java.util.Set; /** * @author Igor Botian <igor.botian@gmail.com> */ public interface RestEndpoint { JsonNode makeRequest(String endpoint, Set<NameValuePair> params) throws IOException; JsonNode makeRequest(String endpoint, Set<NameValuePair> params, Set<NameValuePair> headers) throws IOException; }
igorbotian/rsskit
src/main/java/com/rhcloud/igorbotian/rsskit/rest/RestEndpoint.java
Java
bsd-2-clause
479
# encoding: utf-8 GpbMerchant::Engine.routes.draw do get "gbp/check" => 'gpb#check' get "gbp/pay" => 'gpb#pay' end # draw
dancingbytes/gpb_merchant
config/routes.rb
Ruby
bsd-2-clause
133
(function() { 'use strict' function queryLink() { return { restrict: 'E', scope: { 'query': '=', 'visualization': '=?' }, template: '<a ng-href="{{link}}" class="query-link">{{query.displayname}}</a>', link: function(scope, element) { var hash = null; if (scope.visualization) { if (scope.visualization.type === 'TABLE') { // link to hard-coded table tab instead of the (hidden) visualization tab hash = 'table'; } else { hash = scope.visualization.id; } } scope.link = scope.query.getUrl(false, hash); } } } function querySourceLink($location) { return { restrict: 'E', template: '<span ng-show="query.id && canViewSource">\ <a ng-show="!sourceMode"\ ng-href="{{query.getUrl(true, selectedTab)}}" class="btn btn-default">Show Source\ </a>\ <a ng-show="sourceMode"\ ng-href="{{query.getUrl(false, selectedTab)}}" class="btn btn-default">Hide Source\ </a>\ </span>' } } function queryResultLink() { return { restrict: 'A', link: function (scope, element, attrs) { var fileType = attrs.fileType ? attrs.fileType : "csv"; scope.$watch('queryResult && queryResult.getData()', function(data) { if (!data) { return; } if (scope.queryResult.getId() == null) { element.attr('href', ''); } else { element.attr('href', 'api/queries/' + scope.query.id + '/results/' + scope.queryResult.getId() + '.' + fileType); element.attr('download', scope.query.name.replace(" ", "_") + moment(scope.queryResult.getUpdatedAt()).format("_YYYY_MM_DD") + "." + fileType); } }); } } } // By default Ace will try to load snippet files for the different modes and fail. We don't need them, so we use these // placeholders until we define our own. function defineDummySnippets(mode) { ace.define("ace/snippets/" + mode, ["require", "exports", "module"], function(require, exports, module) { "use strict"; exports.snippetText = ""; exports.scope = mode; }); }; defineDummySnippets("python"); defineDummySnippets("sql"); defineDummySnippets("json"); function queryEditor(QuerySnippet) { return { restrict: 'E', scope: { 'query': '=', 'lock': '=', 'schema': '=', 'syntax': '=' }, template: '<div ui-ace="editorOptions" ng-model="query.query"></div>', link: { pre: function ($scope, element) { $scope.syntax = $scope.syntax || 'sql'; $scope.editorOptions = { mode: 'json', require: ['ace/ext/language_tools'], advanced: { behavioursEnabled: true, enableSnippets: true, enableBasicAutocompletion: true, enableLiveAutocompletion: true, autoScrollEditorIntoView: true, }, onLoad: function(editor) { QuerySnippet.query(function(snippets) { var snippetManager = ace.require("ace/snippets").snippetManager; var m = { snippetText: '' }; m.snippets = snippetManager.parseSnippetFile(m.snippetText); _.each(snippets, function(snippet) { m.snippets.push(snippet.getSnippet()); }); snippetManager.register(m.snippets || [], m.scope); }); editor.$blockScrolling = Infinity; editor.getSession().setUseWrapMode(true); editor.setShowPrintMargin(false); $scope.$watch('syntax', function(syntax) { var newMode = 'ace/mode/' + syntax; editor.getSession().setMode(newMode); }); $scope.$watch('schema', function(newSchema, oldSchema) { if (newSchema !== oldSchema) { var tokensCount = _.reduce(newSchema, function(totalLength, table) { return totalLength + table.columns.length }, 0); // If there are too many tokens we disable live autocomplete, as it makes typing slower. if (tokensCount > 5000) { editor.setOption('enableLiveAutocompletion', false); } else { editor.setOption('enableLiveAutocompletion', true); } } }); $scope.$parent.$on("angular-resizable.resizing", function (event, args) { editor.resize(); }); editor.focus(); } }; var langTools = ace.require("ace/ext/language_tools"); var schemaCompleter = { getCompletions: function(state, session, pos, prefix, callback) { if (prefix.length === 0 || !$scope.schema) { callback(null, []); return; } if (!$scope.schema.keywords) { var keywords = {}; _.each($scope.schema, function (table) { keywords[table.name] = 'Table'; _.each(table.columns, function (c) { keywords[c] = 'Column'; keywords[table.name + "." + c] = 'Column'; }); }); $scope.schema.keywords = _.map(keywords, function(v, k) { return { name: k, value: k, score: 0, meta: v }; }); } callback(null, $scope.schema.keywords); } }; langTools.addCompleter(schemaCompleter); } } }; } function queryFormatter($http, growl) { return { restrict: 'E', // don't create new scope to avoid ui-codemirror bug // seehttps://github.com/angular-ui/ui-codemirror/pull/37 scope: false, template: '<button type="button" class="btn btn-default btn-s"\ ng-click="formatQuery()">\ <span class="zmdi zmdi-format-indent-increase"></span>\ Format Query\ </button>', link: function($scope) { $scope.formatQuery = function formatQuery() { if ($scope.dataSource.syntax == 'json') { try { $scope.query.query = JSON.stringify(JSON.parse($scope.query.query), ' ', 4); } catch(err) { growl.addErrorMessage(err); } } else if ($scope.dataSource.syntax =='sql') { $scope.queryFormatting = true; $http.post('api/queries/format', { 'query': $scope.query.query }).success(function (response) { $scope.query.query = response; }).finally(function () { $scope.queryFormatting = false; }); } else { growl.addInfoMessage("Query formatting is not supported for your data source syntax."); } }; } } } function schemaBrowser() { return { restrict: 'E', scope: { schema: '=' }, templateUrl: '/views/directives/schema_browser.html', link: function ($scope) { $scope.showTable = function(table) { table.collapsed = !table.collapsed; $scope.$broadcast('vsRepeatTrigger'); } $scope.getSize = function(table) { var size = 18; if (!table.collapsed) { size += 18 * table.columns.length; } return size; } } } } function queryTimePicker() { return { restrict: 'E', template: '<select ng-disabled="refreshType != \'daily\'" ng-model="hour" ng-change="updateSchedule()" ng-options="c as c for c in hourOptions"></select> :\ <select ng-disabled="refreshType != \'daily\'" ng-model="minute" ng-change="updateSchedule()" ng-options="c as c for c in minuteOptions"></select>', link: function($scope) { var padWithZeros = function(size, v) { v = String(v); if (v.length < size) { v = "0" + v; } return v; }; $scope.hourOptions = _.map(_.range(0, 24), _.partial(padWithZeros, 2)); $scope.minuteOptions = _.map(_.range(0, 60, 5), _.partial(padWithZeros, 2)); if ($scope.query.hasDailySchedule()) { var parts = $scope.query.scheduleInLocalTime().split(':'); $scope.minute = parts[1]; $scope.hour = parts[0]; } else { $scope.minute = "15"; $scope.hour = "00"; } $scope.updateSchedule = function() { var newSchedule = moment().hour($scope.hour).minute($scope.minute).utc().format('HH:mm'); if (newSchedule != $scope.query.schedule) { $scope.query.schedule = newSchedule; $scope.saveQuery(); } }; $scope.$watch('refreshType', function() { if ($scope.refreshType == 'daily') { $scope.updateSchedule(); } }); } } } function queryRefreshSelect() { return { restrict: 'E', template: '<select\ ng-disabled="refreshType != \'periodic\'"\ ng-model="query.schedule"\ ng-change="saveQuery()"\ ng-options="c.value as c.name for c in refreshOptions">\ <option value="">No Refresh</option>\ </select>', link: function($scope) { $scope.refreshOptions = [ { value: "60", name: '每分钟' } ]; _.each([5, 10, 15, 30], function(i) { $scope.refreshOptions.push({ value: String(i*60), name: "每" + i + "分钟" }) }); _.each(_.range(1, 13), function (i) { $scope.refreshOptions.push({ value: String(i * 3600), name: '每' + i + '小时' }); }) $scope.refreshOptions.push({ value: String(24 * 3600), name: '每24小时' }); $scope.refreshOptions.push({ value: String(7 * 24 * 3600), name: '每7天' }); $scope.refreshOptions.push({ value: String(14 * 24 * 3600), name: '每14天' }); $scope.refreshOptions.push({ value: String(30 * 24 * 3600), name: '每30天' }); $scope.$watch('refreshType', function() { if ($scope.refreshType == 'periodic') { if ($scope.query.hasDailySchedule()) { $scope.query.schedule = null; $scope.saveQuery(); } } }); } } } angular.module('redash.directives') .directive('queryLink', queryLink) .directive('querySourceLink', ['$location', querySourceLink]) .directive('queryResultLink', queryResultLink) .directive('queryEditor', ['QuerySnippet', queryEditor]) .directive('queryRefreshSelect', queryRefreshSelect) .directive('queryTimePicker', queryTimePicker) .directive('schemaBrowser', schemaBrowser) .directive('queryFormatter', ['$http', 'growl', queryFormatter]); })();
guaguadev/redash
rd_ui/app/scripts/directives/query_directives.js
JavaScript
bsd-2-clause
11,659
// ## twig.functions.js // // This file handles parsing filters. module.exports = function (Twig) { /** * @constant * @type {string} */ var TEMPLATE_NOT_FOUND_MESSAGE = 'Template "{name}" is not defined.'; // Determine object type function is(type, obj) { var clas = Object.prototype.toString.call(obj).slice(8, -1); return obj !== undefined && obj !== null && clas === type; } Twig.functions = { // attribute, block, constant, date, dump, parent, random,. // Range function from http://phpjs.org/functions/range:499 // Used under an MIT License range: function (low, high, step) { // http://kevin.vanzonneveld.net // + original by: Waldo Malqui Silva // * example 1: range ( 0, 12 ); // * returns 1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] // * example 2: range( 0, 100, 10 ); // * returns 2: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] // * example 3: range( 'a', 'i' ); // * returns 3: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] // * example 4: range( 'c', 'a' ); // * returns 4: ['c', 'b', 'a'] var matrix = []; var inival, endval, plus; var walker = step || 1; var chars = false; if (!isNaN(low) && !isNaN(high)) { inival = parseInt(low, 10); endval = parseInt(high, 10); } else if (isNaN(low) && isNaN(high)) { chars = true; inival = low.charCodeAt(0); endval = high.charCodeAt(0); } else { inival = (isNaN(low) ? 0 : low); endval = (isNaN(high) ? 0 : high); } plus = ((inival > endval) ? false : true); if (plus) { while (inival <= endval) { matrix.push(((chars) ? String.fromCharCode(inival) : inival)); inival += walker; } } else { while (inival >= endval) { matrix.push(((chars) ? String.fromCharCode(inival) : inival)); inival -= walker; } } return matrix; }, cycle: function(arr, i) { var pos = i % arr.length; return arr[pos]; }, dump: function() { var EOL = '\n', indentChar = ' ', indentTimes = 0, out = '', args = Array.prototype.slice.call(arguments), indent = function(times) { var ind = ''; while (times > 0) { times--; ind += indentChar; } return ind; }, displayVar = function(variable) { out += indent(indentTimes); if (typeof(variable) === 'object') { dumpVar(variable); } else if (typeof(variable) === 'function') { out += 'function()' + EOL; } else if (typeof(variable) === 'string') { out += 'string(' + variable.length + ') "' + variable + '"' + EOL; } else if (typeof(variable) === 'number') { out += 'number(' + variable + ')' + EOL; } else if (typeof(variable) === 'boolean') { out += 'bool(' + variable + ')' + EOL; } }, dumpVar = function(variable) { var i; if (variable === null) { out += 'NULL' + EOL; } else if (variable === undefined) { out += 'undefined' + EOL; } else if (typeof variable === 'object') { out += indent(indentTimes) + typeof(variable); indentTimes++; out += '(' + (function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) { size++; } } return size; })(variable) + ') {' + EOL; for (i in variable) { out += indent(indentTimes) + '[' + i + ']=> ' + EOL; displayVar(variable[i]); } indentTimes--; out += indent(indentTimes) + '}' + EOL; } else { displayVar(variable); } }; // handle no argument case by dumping the entire render context if (args.length == 0) args.push(this.context); Twig.forEach(args, function(variable) { dumpVar(variable); }); return out; }, date: function(date, time) { var dateObj; if (date === undefined) { dateObj = new Date(); } else if (Twig.lib.is("Date", date)) { dateObj = date; } else if (Twig.lib.is("String", date)) { if (date.match(/^[0-9]+$/)) { dateObj = new Date(date * 1000); } else { dateObj = new Date(Twig.lib.strtotime(date) * 1000); } } else if (Twig.lib.is("Number", date)) { // timestamp dateObj = new Date(date * 1000); } else { throw new Twig.Error("Unable to parse date " + date); } return dateObj; }, block: function(block) { if (this.originalBlockTokens[block]) { return Twig.logic.parse.apply(this, [this.originalBlockTokens[block], this.context]).output; } else { return this.blocks[block]; } }, parent: function() { // Add a placeholder return Twig.placeholders.parent; }, attribute: function(object, method, params) { if (Twig.lib.is('Object', object)) { if (object.hasOwnProperty(method)) { if (typeof object[method] === "function") { return object[method].apply(undefined, params); } else { return object[method]; } } } // Array will return element 0-index return object[method] || undefined; }, max: function(values) { if(Twig.lib.is("Object", values)) { delete values["_keys"]; return Twig.lib.max(values); } return Twig.lib.max.apply(null, arguments); }, min: function(values) { if(Twig.lib.is("Object", values)) { delete values["_keys"]; return Twig.lib.min(values); } return Twig.lib.min.apply(null, arguments); }, template_from_string: function(template) { if (template === undefined) { template = ''; } return Twig.Templates.parsers.twig({ options: this.options, data: template }); }, random: function(value) { var LIMIT_INT31 = 0x80000000; function getRandomNumber(n) { var random = Math.floor(Math.random() * LIMIT_INT31); var limits = [0, n]; var min = Math.min.apply(null, limits), max = Math.max.apply(null, limits); return min + Math.floor((max - min + 1) * random / LIMIT_INT31); } if(Twig.lib.is("Number", value)) { return getRandomNumber(value); } if(Twig.lib.is("String", value)) { return value.charAt(getRandomNumber(value.length-1)); } if(Twig.lib.is("Array", value)) { return value[getRandomNumber(value.length-1)]; } if(Twig.lib.is("Object", value)) { var keys = Object.keys(value); return value[keys[getRandomNumber(keys.length-1)]]; } return getRandomNumber(LIMIT_INT31-1); }, /** * Returns the content of a template without rendering it * @param {string} name * @param {boolean} [ignore_missing=false] * @returns {string} */ source: function(name, ignore_missing) { var templateSource; var templateFound = false; var isNodeEnvironment = typeof module !== 'undefined' && typeof module.exports !== 'undefined' && typeof window === 'undefined'; var loader; var path; //if we are running in a node.js environment, set the loader to 'fs' and ensure the // path is relative to the CWD of the running script //else, set the loader to 'ajax' and set the path to the value of name if (isNodeEnvironment) { loader = 'fs'; path = __dirname + '/' + name; } else { loader = 'ajax'; path = name; } //build the params object var params = { id: name, path: path, method: loader, parser: 'source', async: false, fetchTemplateSource: true }; //default ignore_missing to false if (typeof ignore_missing === 'undefined') { ignore_missing = false; } //try to load the remote template // //on exception, log it try { templateSource = Twig.Templates.loadRemote(name, params); //if the template is undefined or null, set the template to an empty string and do NOT flip the // boolean indicating we found the template // //else, all is good! flip the boolean indicating we found the template if (typeof templateSource === 'undefined' || templateSource === null) { templateSource = ''; } else { templateFound = true; } } catch (e) { Twig.log.debug('Twig.functions.source: ', 'Problem loading template ', e); } //if the template was NOT found AND we are not ignoring missing templates, return the same message // that is returned by the PHP implementation of the twig source() function // //else, return the template source if (!templateFound && !ignore_missing) { return TEMPLATE_NOT_FOUND_MESSAGE.replace('{name}', name); } else { return templateSource; } } }; Twig._function = function(_function, value, params) { if (!Twig.functions[_function]) { throw "Unable to find function " + _function; } return Twig.functions[_function](value, params); }; Twig._function.extend = function(_function, definition) { Twig.functions[_function] = definition; }; return Twig; };
dave-irvine/twig.js
src/twig.functions.js
JavaScript
bsd-2-clause
11,876
namespace Zametek.Event.ProjectPlan { public class GraphCompiledPayload { } }
countincognito/Zametek.ProjectPlan
src/Zametek.Event.ProjectPlan/GraphCompiledPayload.cs
C#
bsd-2-clause
93
# -*- coding: utf-8 -*- """ The scheduler is responsible for the module handling. """ import modules from importlib import import_module from additional.Logging import Logging ################################################################################ class Scheduler(): """ This class instantiates the modules, takes care of the module's versions and gets the module's select queries. """ # dictonary of instantiated modules _instantiated_modules = {} def __init__(self, db): self._db = db self._log = Logging(self.__class__.__name__).get_logger() ######################################################################## self._instantiate_modules() self._check_module_versions() ############################################################################ def _instantiate_modules(self): """ Method to instantiate modules. All modules must contain a class with the exact same name as the module. This class must implement the abstract base class (abc) DatasourceBase. """ # finds all modules to import for module_name in modules.__all__: # imports an instantiates the module by name module = import_module('modules.' + module_name) module = getattr(module, module_name)() # makes sure the module implements DatasourceBase if not isinstance(module, modules.DatasourceBase): raise SubClassError( 'Modul is not an instance of DatasourceBase: {}' .format(module.__class__.__name__)) # adds the module to the list of instantieated modules self._instantiated_modules[module.__class__.__name__] = module ############################################################################ def _check_module_versions(self): """ Method to check module's versions. """ for module_name, module in self._instantiated_modules.items(): module_version = module.get_version() # searches module's version in the database result = self._db.select_data(''' SELECT version FROM versions WHERE module = %s''', (module_name,)) if not result: # appends the module with it's version to the database self._db.insert_data(''' INSERT INTO versions (module, version) VALUES (%s, %s)''', (module_name, module_version)) elif result[0][0] < module_version: # updates the request entry self.server.db.update_data(''' UPDATE versions SET version = %s WHERE module = %s''', (module_version, module_name,)) elif result[0][0] > module_version: raise VersionError('Old module version detected!' + 'Module: {} - Expected: {} - Found: {}' .format(module_name, result[0][0], module_version)) ############################################################################ def get_module_select_queries(self): """ Returns the module's search queries. """ queries = {} for module_name, module in self._instantiated_modules.items(): queries[module_name] = module.get_queries('select') return queries ################################################################################ class SubClassError(Exception): """ Exception for module subclass errors. """ class VersionError(Exception): """ Exception for module version errors. """
andreas-kowasch/DomainSearch
DomainSearchViewer/additional/Scheduler.py
Python
bsd-2-clause
3,767
package com.github.bednar.components.inject.service; import javax.annotation.Nonnull; /** * @author Jakub Bednář (07/01/2014 20:59) */ public final class CoffeeCompilerCfg { private Boolean bare = false; private CoffeeCompilerCfg() { } @Nonnull public static CoffeeCompilerCfg build() { return new CoffeeCompilerCfg(); } @Nonnull public Boolean getBare() { return bare; } @Nonnull public CoffeeCompilerCfg setBare(@Nonnull final Boolean bare) { this.bare = Boolean.TRUE.equals(bare); return this; } }
bednar/components
src/main/java/com/github/bednar/components/inject/service/CoffeeCompilerCfg.java
Java
bsd-2-clause
608
from django.conf.urls import patterns, include, url from django.shortcuts import redirect, render_to_response from django.template.context import RequestContext # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() # Just redirect / to /blog for now until I can # come up with something to put on the homepage.. def to_blog(request): return redirect('/blog/', permanent=False) # Follow the BSD license and allow the source/binary to reproduce # the license and copyright message def sslicense(request): slicense = """ Copyright (c) 2012-2013 Justin Crawford <Justasic@gmail.com> 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. 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 HOLDER 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 """ ctx = { 'parts': { "title": "License", "html_title": "License", "fragment": slicense.replace('\n', '<br>'), }, } return render_to_response('docs/docs.html', RequestContext(request, ctx)) urlpatterns = patterns('', # Examples: # url(r'^$', 'StackSmash.views.home', name='home'), # url(r'^StackSmash/', include('StackSmash.foo.urls')), # TODO: Fix index and use something... Should identify subdomains somehow.. #url(r'^$', include('StackSmash.apps.blog.urls')), url(r'^license/', sslicense, name='license'), #url(r'^docs/', include('StackSmash.apps.docs.urls'), name='docs', app_name='docs'), url(r'^blog/', include('StackSmash.apps.blog.urls', namespace='blog')), url(r'^projects/', include('StackSmash.apps.projects.urls', namespace='projects')), url(r'^upload/', include('StackSmash.apps.uploader.urls', namespace='upload')), url(r'^$', to_blog, name='index'), #url(r'^projects/', include('StackSmash.apps.projects.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls), name='admin'), )
Justasic/StackSmash
StackSmash/urls.py
Python
bsd-2-clause
3,146
package de.bht.ebus.spotsome.model; import java.util.Objects; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Table; import org.springframework.data.domain.Persistable; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonView; import de.bht.ebus.spotsome.util.JsonViews; @Entity @Table(name = "spot") @Access(AccessType.FIELD) @JsonAutoDetect(fieldVisibility=Visibility.ANY, getterVisibility=Visibility.NONE, isGetterVisibility=Visibility.NONE) public class Spot implements Persistable<Long> { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "spot_id") @JsonView({JsonViews.OnlyId.class, JsonViews.Public.class}) @JsonProperty("spot_id") private Long spotId; @Column(nullable = false) @JsonView(JsonViews.Public.class) private String name; /** * The radius around the location in meters */ @Column(nullable = false) @JsonView(JsonViews.Public.class) private double radius; @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) @JoinColumn(name = "location_id", nullable = false) @JsonView(JsonViews.Public.class) private Location location; @OneToOne @JoinColumn(name = "user_fk", nullable = false, updatable = false) @JsonIgnore private User owner; public Spot(String name, double radius, Location location, User owner) { setName(name); setRadius(radius); setLocation(location); this.owner = Objects.requireNonNull(owner); } protected Spot() { } public Long getId() { return spotId; } public String getName() { return name; } public void setName(String name) { this.name = Objects.requireNonNull(name); } public double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = Objects.requireNonNull(location); } public User getOwner() { return owner; } @Override public boolean isNew() { return spotId == null && location.getLocationId() == null; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((spotId == null) ? 0 : spotId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Spot other = (Spot) obj; if (spotId == null) { if (other.spotId != null) return false; } else if (!spotId.equals(other.spotId)) return false; return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Spot [spotId="); builder.append(spotId); builder.append(", name="); builder.append(name); builder.append(", radius="); builder.append(radius); builder.append(", location="); builder.append(location); builder.append(", owner="); builder.append(owner); builder.append("]"); return builder.toString(); } }
steven-maasch/spotsome
de.bht.ebus.spotsome/src/main/java/de/bht/ebus/spotsome/model/Spot.java
Java
bsd-2-clause
3,630
#include <nano/node/bootstrap/bootstrap.hpp> #include <nano/node/bootstrap/bootstrap_bulk_push.hpp> #include <nano/node/node.hpp> #include <nano/node/transport/tcp.hpp> nano::bulk_push_client::bulk_push_client (std::shared_ptr<nano::bootstrap_client> const & connection_a) : connection (connection_a) { } nano::bulk_push_client::~bulk_push_client () { } void nano::bulk_push_client::start () { nano::bulk_push message; auto this_l (shared_from_this ()); connection->channel->send ( message, [this_l](boost::system::error_code const & ec, size_t size_a) { auto transaction (this_l->connection->node->store.tx_begin_read ()); if (!ec) { this_l->push (transaction); } else { if (this_l->connection->node->config.logging.bulk_pull_logging ()) { this_l->connection->node->logger.try_log (boost::str (boost::format ("Unable to send bulk_push request: %1%") % ec.message ())); } } }, false); // is bootstrap traffic is_droppable false } void nano::bulk_push_client::push (nano::transaction const & transaction_a) { std::shared_ptr<nano::block> block; bool finished (false); while (block == nullptr && !finished) { if (current_target.first.is_zero () || current_target.first == current_target.second) { nano::lock_guard<std::mutex> guard (connection->attempt->mutex); if (!connection->attempt->bulk_push_targets.empty ()) { current_target = connection->attempt->bulk_push_targets.back (); connection->attempt->bulk_push_targets.pop_back (); } else { finished = true; } } if (!finished) { block = connection->node->store.block_get (transaction_a, current_target.first); if (block == nullptr) { current_target.first = nano::block_hash (0); } else { if (connection->node->config.logging.bulk_pull_logging ()) { connection->node->logger.try_log ("Bulk pushing range ", current_target.first.to_string (), " down to ", current_target.second.to_string ()); } } } } if (finished) { send_finished (); } else { current_target.first = block->previous (); push_block (*block); } } void nano::bulk_push_client::send_finished () { nano::shared_const_buffer buffer (static_cast<uint8_t> (nano::block_type::not_a_block)); auto this_l (shared_from_this ()); connection->channel->send_buffer (buffer, nano::stat::detail::all, [this_l](boost::system::error_code const & ec, size_t size_a) { try { this_l->promise.set_value (false); } catch (std::future_error &) { } }); } void nano::bulk_push_client::push_block (nano::block const & block_a) { std::vector<uint8_t> buffer; { nano::vectorstream stream (buffer); nano::serialize_block (stream, block_a); } auto this_l (shared_from_this ()); connection->channel->send_buffer (nano::shared_const_buffer (std::move (buffer)), nano::stat::detail::all, [this_l](boost::system::error_code const & ec, size_t size_a) { if (!ec) { auto transaction (this_l->connection->node->store.tx_begin_read ()); this_l->push (transaction); } else { if (this_l->connection->node->config.logging.bulk_pull_logging ()) { this_l->connection->node->logger.try_log (boost::str (boost::format ("Error sending block during bulk push: %1%") % ec.message ())); } } }); } nano::bulk_push_server::bulk_push_server (std::shared_ptr<nano::bootstrap_server> const & connection_a) : receive_buffer (std::make_shared<std::vector<uint8_t>> ()), connection (connection_a) { receive_buffer->resize (256); } void nano::bulk_push_server::throttled_receive () { if (!connection->node->block_processor.half_full ()) { receive (); } else { auto this_l (shared_from_this ()); connection->node->alarm.add (std::chrono::steady_clock::now () + std::chrono::seconds (1), [this_l]() { if (!this_l->connection->stopped) { this_l->throttled_receive (); } }); } } void nano::bulk_push_server::receive () { if (connection->node->bootstrap_initiator.in_progress ()) { if (connection->node->config.logging.bulk_pull_logging ()) { connection->node->logger.try_log ("Aborting bulk_push because a bootstrap attempt is in progress"); } } else { auto this_l (shared_from_this ()); connection->socket->async_read (receive_buffer, 1, [this_l](boost::system::error_code const & ec, size_t size_a) { if (!ec) { this_l->received_type (); } else { if (this_l->connection->node->config.logging.bulk_pull_logging ()) { this_l->connection->node->logger.try_log (boost::str (boost::format ("Error receiving block type: %1%") % ec.message ())); } } }); } } void nano::bulk_push_server::received_type () { auto this_l (shared_from_this ()); nano::block_type type (static_cast<nano::block_type> (receive_buffer->data ()[0])); switch (type) { case nano::block_type::send: { connection->node->stats.inc (nano::stat::type::bootstrap, nano::stat::detail::send, nano::stat::dir::in); connection->socket->async_read (receive_buffer, nano::send_block::size, [this_l, type](boost::system::error_code const & ec, size_t size_a) { this_l->received_block (ec, size_a, type); }); break; } case nano::block_type::receive: { connection->node->stats.inc (nano::stat::type::bootstrap, nano::stat::detail::receive, nano::stat::dir::in); connection->socket->async_read (receive_buffer, nano::receive_block::size, [this_l, type](boost::system::error_code const & ec, size_t size_a) { this_l->received_block (ec, size_a, type); }); break; } case nano::block_type::open: { connection->node->stats.inc (nano::stat::type::bootstrap, nano::stat::detail::open, nano::stat::dir::in); connection->socket->async_read (receive_buffer, nano::open_block::size, [this_l, type](boost::system::error_code const & ec, size_t size_a) { this_l->received_block (ec, size_a, type); }); break; } case nano::block_type::change: { connection->node->stats.inc (nano::stat::type::bootstrap, nano::stat::detail::change, nano::stat::dir::in); connection->socket->async_read (receive_buffer, nano::change_block::size, [this_l, type](boost::system::error_code const & ec, size_t size_a) { this_l->received_block (ec, size_a, type); }); break; } case nano::block_type::state: { connection->node->stats.inc (nano::stat::type::bootstrap, nano::stat::detail::state_block, nano::stat::dir::in); connection->socket->async_read (receive_buffer, nano::state_block::size, [this_l, type](boost::system::error_code const & ec, size_t size_a) { this_l->received_block (ec, size_a, type); }); break; } case nano::block_type::not_a_block: { connection->finish_request (); break; } default: { if (connection->node->config.logging.network_packet_logging ()) { connection->node->logger.try_log ("Unknown type received as block type"); } break; } } } void nano::bulk_push_server::received_block (boost::system::error_code const & ec, size_t size_a, nano::block_type type_a) { if (!ec) { nano::bufferstream stream (receive_buffer->data (), size_a); auto block (nano::deserialize_block (stream, type_a)); if (block != nullptr && !nano::work_validate (*block)) { connection->node->process_active (std::move (block)); throttled_receive (); } else { if (connection->node->config.logging.bulk_pull_logging ()) { connection->node->logger.try_log ("Error deserializing block received from pull request"); } } } }
SergiySW/raiblocks
nano/node/bootstrap/bootstrap_bulk_push.cpp
C++
bsd-2-clause
7,471
package io.iron.ironworker.client.builders; import java.util.Date; import java.util.HashMap; import java.util.Map; public class ScheduleOptionsObject { private Map<String, Object> options; public ScheduleOptionsObject() { options = new HashMap<String, Object>(); } public ScheduleOptionsObject priority(int priority) { options.put("priority", priority); return this; } public ScheduleOptionsObject startAt(Date startAt) { options.put("start_at", startAt); return this; } public ScheduleOptionsObject endAt(Date endAt) { options.put("end_at", endAt); return this; } public ScheduleOptionsObject delay(int delay) { options.put("delay", delay); return this; } public ScheduleOptionsObject runEvery(int runEvery) { options.put("run_every", runEvery); return this; } public ScheduleOptionsObject runTimes(int runTimes) { options.put("run_times", runTimes); return this; } public ScheduleOptionsObject cluster(String cluster) { options.put("cluster", cluster); return this; } public ScheduleOptionsObject label(String label) { options.put("label", label); return this; } public ScheduleOptionsObject encryptionKey(String encryptionKey) { options.put("encryptionKey", encryptionKey); return this; } public ScheduleOptionsObject encryptionKeyFile(String encryptionKeyFile) { options.put("encryptionKeyFile", encryptionKeyFile); return this; } public Map<String, Object> create() { return options; } }
iron-io/iron_worker_java
src/main/java/io/iron/ironworker/client/builders/ScheduleOptionsObject.java
Java
bsd-2-clause
1,705
/* * Copyright (c) 2008, Christophe Delory * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * THIS SOFTWARE IS PROVIDED BY CHRISTOPHE DELORY ``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 CHRISTOPHE DELORY 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. */ package christophedelory.playlist.wpl; /** * Contains the elements that define the contents of a playlist. * The contents of a playlist are organized within a seq element that is contained within the body element. * Typically there is either one seq element that defines a static set of media items and contains media elements, * or there is one that defines a dynamic set of media items and contains a smartPlaylist element. * <br> * Windows Media Player 9 Series or later. * @version $Revision: 92 $ * @author Christophe Delory * @castor.class xml="body" */ public class Body { /** * The body sequence. */ private Seq _seq = new Seq(); /** * Returns the body sequence. * @return a sequence. Shall not be <code>null</code>. * @see #setSeq * @castor.field * get-method="getSeq" * set-method="setSeq" * required="true" * @castor.field-xml * name="seq" * node="element" */ public Seq getSeq() { return _seq; } /** * Initializes the body sequence. * @param seq a sequence. Shall not be <code>null</code>. * @throws NullPointerException if <code>seq</code> is <code>null</code>. * @see #getSeq */ public void setSeq(final Seq seq) { if (seq == null) { throw new NullPointerException("No body sequence"); } _seq = seq; } }
wenerme/Lizzy
src/java/christophedelory/playlist/wpl/Body.java
Java
bsd-2-clause
2,760
require 'roman' TestCase String do Method :to_roman do test "single digit conversions" do "I".to_roman.assert == RomanNumeral.new(1) "V".to_roman.assert == RomanNumeral.new(5) "X".to_roman.assert == RomanNumeral.new(10) "i".to_roman.assert == RomanNumeral.new(1) "v".to_roman.assert == RomanNumeral.new(5) "x".to_roman.assert == RomanNumeral.new(10) end test "simple mulit-digit conversions" do "IV".to_roman.assert == RomanNumeral.new(4) "VI".to_roman.assert == RomanNumeral.new(6) "VII".to_roman.assert == RomanNumeral.new(7) "VIII".to_roman.assert == RomanNumeral.new(8) "IX".to_roman.assert == RomanNumeral.new(9) "XI".to_roman.assert == RomanNumeral.new(11) "XII".to_roman.assert == RomanNumeral.new(12) "XIII".to_roman.assert == RomanNumeral.new(13) end test "complex conversions" do "XXIV".to_roman.assert == RomanNumeral.new(24) end end end
rubyworks/roman
test/string_case.rb
Ruby
bsd-2-clause
986
// Copyright (c) 2012, Andre Caron (andre.l.caron@gmail.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * 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. // // 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 HOLDER 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. /*! * @file * @brief C++ demo program. */ #include <chttp.hpp> #include <iostream> int main (int argc, char ** argv) { // Prepare. http::Head head(4*1024); // Acquire. head.push("Content-Length", "123"); head.push("Content-Type", "application/json"); // Iterate. http::Cursor cursor(head); while (cursor.next()) { std::cout << "'" << cursor.field() << "': '" << cursor.value() << "'." << std::endl; } // Search. std::cout << "size: '" << head.find("Content-Length") << "'." << std::endl << "data: '" << head.find("Content-Type") << "'." << std::endl << "auth: '" << head.find("Authorization") << "'." << std::endl; }
AndreLouisCaron/chttp
demo/demo.cpp
C++
bsd-2-clause
2,153
/* This file is part of the WebKit open source project. This file has been generated by generate-bindings.pl. DO NOT MODIFY! This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "config.h" #include "V8File.h" #include "RuntimeEnabledFeatures.h" #include "V8Binding.h" #include "V8BindingState.h" #include "V8Blob.h" #include "V8DOMWrapper.h" #include "V8IsolatedContext.h" #include "V8Proxy.h" #include <wtf/UnusedParam.h> namespace WebCore { WrapperTypeInfo V8File::info = { V8File::GetTemplate, V8File::derefObject, 0, &V8Blob::info }; namespace FileInternal { template <typename T> void V8_USE(T) { } static v8::Handle<v8::Value> nameAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.File.name._get"); File* imp = V8File::toNative(info.Holder()); return v8String(imp->name()); } static v8::Handle<v8::Value> lastModifiedDateAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.File.lastModifiedDate._get"); File* imp = V8File::toNative(info.Holder()); return v8DateOrNull(imp->lastModifiedDate()); } static v8::Handle<v8::Value> webkitRelativePathAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.File.webkitRelativePath._get"); File* imp = V8File::toNative(info.Holder()); return v8String(imp->webkitRelativePath()); } static v8::Handle<v8::Value> fileNameAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.File.fileName._get"); File* imp = V8File::toNative(info.Holder()); return v8String(imp->fileName()); } static v8::Handle<v8::Value> fileSizeAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.File.fileSize._get"); File* imp = V8File::toNative(info.Holder()); return v8::Number::New(static_cast<double>(imp->fileSize())); } } // namespace FileInternal static const BatchedAttribute FileAttrs[] = { // Attribute 'name' (Type: 'readonly attribute' ExtAttr: '') {"name", FileInternal::nameAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'lastModifiedDate' (Type: 'readonly attribute' ExtAttr: '') {"lastModifiedDate", FileInternal::lastModifiedDateAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'webkitRelativePath' (Type: 'readonly attribute' ExtAttr: '') {"webkitRelativePath", FileInternal::webkitRelativePathAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'fileName' (Type: 'readonly attribute' ExtAttr: '') {"fileName", FileInternal::fileNameAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'fileSize' (Type: 'readonly attribute' ExtAttr: '') {"fileSize", FileInternal::fileSizeAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, }; static v8::Persistent<v8::FunctionTemplate> ConfigureV8FileTemplate(v8::Persistent<v8::FunctionTemplate> desc) { desc->ReadOnlyPrototype(); v8::Local<v8::Signature> defaultSignature = configureTemplate(desc, "File", V8Blob::GetTemplate(), V8File::internalFieldCount, FileAttrs, WTF_ARRAY_LENGTH(FileAttrs), 0, 0); UNUSED_PARAM(defaultSignature); // In some cases, it will not be used. // Custom toString template desc->Set(getToStringName(), getToStringTemplate()); return desc; } v8::Persistent<v8::FunctionTemplate> V8File::GetRawTemplate() { V8BindingPerIsolateData* data = V8BindingPerIsolateData::current(); V8BindingPerIsolateData::TemplateMap::iterator result = data->rawTemplateMap().find(&info); if (result != data->rawTemplateMap().end()) return result->second; v8::HandleScope handleScope; v8::Persistent<v8::FunctionTemplate> templ = createRawTemplate(); data->rawTemplateMap().add(&info, templ); return templ; } v8::Persistent<v8::FunctionTemplate> V8File::GetTemplate() { V8BindingPerIsolateData* data = V8BindingPerIsolateData::current(); V8BindingPerIsolateData::TemplateMap::iterator result = data->templateMap().find(&info); if (result != data->templateMap().end()) return result->second; v8::HandleScope handleScope; v8::Persistent<v8::FunctionTemplate> templ = ConfigureV8FileTemplate(GetRawTemplate()); data->templateMap().add(&info, templ); return templ; } bool V8File::HasInstance(v8::Handle<v8::Value> value) { return GetRawTemplate()->HasInstance(value); } v8::Handle<v8::Object> V8File::wrapSlow(File* impl) { v8::Handle<v8::Object> wrapper; V8Proxy* proxy = 0; wrapper = V8DOMWrapper::instantiateV8Object(proxy, &info, impl); if (wrapper.IsEmpty()) return wrapper; impl->ref(); v8::Persistent<v8::Object> wrapperHandle = v8::Persistent<v8::Object>::New(wrapper); if (!hasDependentLifetime) wrapperHandle.MarkIndependent(); getDOMObjectMap().set(impl, wrapperHandle); return wrapper; } void V8File::derefObject(void* object) { static_cast<File*>(object)->deref(); } } // namespace WebCore
Treeeater/WebPermission
src_chrome_Release_obj_global_intermediate_webcore/bindings/V8File.cpp
C++
bsd-2-clause
6,223
class Libphonenumber < Formula desc "C++ Phone Number library by Google" homepage "https://github.com/googlei18n/libphonenumber" url "https://github.com/googlei18n/libphonenumber/archive/libphonenumber-7.5.2.tar.gz" sha256 "c116c1299074b10ed8b862221ca57f822bae7637b717706ff2c71350f430b3b1" bottle do cellar :any sha256 "94e3ae2fa673a715cc920afe1735f77937e1c3ba74835e2c313b0e2a51fafd0b" => :el_capitan sha256 "909df5e61993716764df96f22839bf0b1f0669b05077d0fa4f04dc7ffdbe5cc9" => :yosemite sha256 "e53f237071882b92ebeca368d63aac3843f2cbb33191e97b5915c2e133ef296e" => :mavericks end depends_on "cmake" => :build depends_on :java => "1.7+" depends_on "icu4c" depends_on "protobuf" depends_on "boost" depends_on "re2" resource "gtest" do url "https://googletest.googlecode.com/files/gtest-1.7.0.zip" sha256 "247ca18dd83f53deb1328be17e4b1be31514cedfc1e3424f672bf11fd7e0d60d" end def install (buildpath/"gtest").install resource("gtest") cd "gtest" do system "cmake", ".", *std_cmake_args system "make" end args = std_cmake_args + %W[ -DGTEST_INCLUDE_DIR:PATH=#{buildpath}/gtest/include -DGTEST_LIB:PATH=#{buildpath}/gtest/libgtest.a -DGTEST_SOURCE_DIR:PATH=#{buildpath}/gtest/src ] system "cmake", "cpp", *args system "make", "install" end test do (testpath/"test.cpp").write <<-EOS.undent #include <phonenumbers/phonenumberutil.h> #include <phonenumbers/phonenumber.pb.h> #include <iostream> #include <string> using namespace i18n::phonenumbers; int main() { PhoneNumberUtil *phone_util_ = PhoneNumberUtil::GetInstance(); PhoneNumber test_number; string formatted_number; test_number.set_country_code(1); test_number.set_national_number(6502530000ULL); phone_util_->Format(test_number, PhoneNumberUtil::E164, &formatted_number); if (formatted_number == "+16502530000") { return 0; } else { return 1; } } EOS system ENV.cxx, "test.cpp", "-L#{lib}", "-lphonenumber", "-o", "test" system "./test" end end
ShivaHuang/homebrew-core
Formula/libphonenumber.rb
Ruby
bsd-2-clause
2,175
define( ['helper/english', 'vendor/underscore'], function(englishHelper, _){ var persons, irregularVerbs; /** * @type {Array} */ persons = ['s1', 's2', 's3', 'p1', 'p2', 'p3']; irregularVerbs = { be: { present: ['am', 'are', 'is', 'are', 'are', 'are'], past: ['was', 'were', 'was', 'were', 'were', 'were'] }, have: { present: 'has', past: 'had' } }; /** * * @param {String} verb * @param {String} person * @return {Object} */ function irregularPresent(verb, person) { var result = false, personIndex; if (typeof irregularVerbs[verb] != 'undefined' && typeof irregularVerbs[verb].present != 'undefined') { result = irregularVerbs[verb].present; if (_.isArray(result)) { personIndex = persons.indexOf(person); return {result: result[personIndex], personalize: false}; } if ('s3' == person) { return {result: result, personalize: false}; } } return {result: verb, personalize: true}; } /** * * @param {String} defaultForm present tense, plural, 3rd person * @param {String} person to use, one of s1-s3, p1-p3 * @return {String} */ function personalize(defaultForm, person){ var shortenedVerb; switch (person) { case 's3': shortenedVerb = defaultForm.substr(0, defaultForm.length - 1); if (englishHelper.checkConsonantEnding(shortenedVerb)) { if (defaultForm[defaultForm.length-1] == 'y') { return shortenedVerb + 'ies'; } else if (defaultForm[defaultForm.length-1] == 'o') { return defaultForm + 'es'; } } return defaultForm + 's'; default: return defaultForm; } } /** * * @param {String} defaultForm present tense, plural, 3rd person * @param {String} person to use, one of s1-s3, p1-p3 * @return {*} */ function present(defaultForm, person){ var irregularResult, personIndex; personIndex = persons.indexOf(person); if (personIndex == -1) { throw 'Given person is not allowed'; } irregularResult = irregularPresent(defaultForm, person); if (irregularResult.personalize) { return personalize(irregularResult.result, person); } return irregularResult.result; } return { present: present }; } );
peteraba/deutschodoro
app/library/english/verb.js
JavaScript
bsd-2-clause
3,037
<?php /** * \Pyrus\PackageFile\v2Iterator\FileContentsMulti * * PHP version 5 * * @category Pyrus * @package Pyrus * @author Greg Beaver <cellog@php.net> * @copyright 2010 The PEAR Group * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @link https://github.com/pyrus/Pyrus */ namespace Pyrus\PackageFile\v2Iterator; /** * iterator for tags with multiple sub-tags * * @category Pyrus * @package Pyrus * @author Greg Beaver <cellog@php.net> * @copyright 2010 The PEAR Group * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @link https://github.com/pyrus/Pyrus */ class FileContentsMulti extends FileContents { function key() { return $this->tag; } }
pyrus/Pyrus
src/Pyrus/PackageFile/v2Iterator/FileContentsMulti.php
PHP
bsd-2-clause
778