repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
train-ticket
train-ticket-master/ts-verification-code-service/src/main/java/verifycode/service/impl/VerifyCodeServiceImpl.java
package verifycode.service.impl; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; import verifycode.service.VerifyCodeService; import verifycode.util.CookieUtil; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.UUID; import java.util.concurrent.TimeUnit; /** * @author fdse */ @Service public class VerifyCodeServiceImpl implements VerifyCodeService { public static final int CAPTCHA_EXPIRED = 1000; private static final Logger LOGGER = LoggerFactory.getLogger(VerifyCodeServiceImpl.class); String ysbCaptcha = "YsbCaptcha"; /** * build local cache */ public Cache<String, String> cacheCode = CacheBuilder.newBuilder() // max size .maximumSize(CAPTCHA_EXPIRED) .expireAfterAccess(CAPTCHA_EXPIRED, TimeUnit.SECONDS) .build(); private static char mapTable[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; @Override public Map<String, Object> getImageCode(int width, int height, OutputStream os, HttpServletRequest request, HttpServletResponse response, HttpHeaders headers) { Map<String, Object> returnMap = new HashMap<>(); if (width <= 0) { width = 60; } if (height <= 0) { height = 20; } BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); Random random = new Random(); //NOSONAR g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); g.setFont(new Font("Times New Roman", Font.PLAIN, 18)); g.setColor(getRandColor(160, 200)); for (int i = 0; i < 168; i++) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x, y, x + xl, y + yl); } String strEnsure = ""; for (int i = 0; i < 4; ++i) { strEnsure += mapTable[(int) (mapTable.length * Math.random())]; g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110))); String str = strEnsure.substring(i, i + 1); g.drawString(str, 13 * i + 6, 16); } g.dispose(); returnMap.put("image", image); returnMap.put("strEnsure", strEnsure); Cookie cookie = CookieUtil.getCookieByName(request, ysbCaptcha); String cookieId; if (cookie == null) { VerifyCodeServiceImpl.LOGGER.warn("[getImageCode][Get image code warn.Cookie not found][Path Info: {}]",request.getPathInfo()); cookieId = UUID.randomUUID().toString().replace("-", "").toUpperCase(); CookieUtil.addCookie(response, ysbCaptcha, cookieId, CAPTCHA_EXPIRED); } else { if (cookie.getValue() != null) { cookieId = UUID.randomUUID().toString().replace("-", "").toUpperCase(); CookieUtil.addCookie(response, ysbCaptcha, cookieId, CAPTCHA_EXPIRED); } else { cookieId = cookie.getValue(); } } VerifyCodeServiceImpl.LOGGER.info("[getImageCode][strEnsure: {}]", strEnsure); cacheCode.put(cookieId, strEnsure); return returnMap; } @Override public boolean verifyCode(HttpServletRequest request, HttpServletResponse response, String receivedCode, HttpHeaders headers) { boolean result = false; Cookie cookie = CookieUtil.getCookieByName(request, ysbCaptcha); String cookieId; if (cookie == null) { VerifyCodeServiceImpl.LOGGER.warn("[verifyCode][Verify code warn][Cookie not found][Path Info: {}]",request.getPathInfo()); cookieId = UUID.randomUUID().toString().replace("-", "").toUpperCase(); CookieUtil.addCookie(response, ysbCaptcha, cookieId, CAPTCHA_EXPIRED); } else { cookieId = cookie.getValue(); } String code = cacheCode.getIfPresent(cookieId); LOGGER.info("GET Code By cookieId " + cookieId + " is :" + code); if (code == null) { VerifyCodeServiceImpl.LOGGER.warn("[verifyCode][Get image code warn][Code not found][CookieId: {}]",cookieId); return false; } if (code.equalsIgnoreCase(receivedCode)) { result = true; } return result; } static Color getRandColor(int fc, int bc) { Random random = new Random(); //NOSONAR if (fc > 255) { fc = 255; } if (bc > 255) { bc = 255; } int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } }
5,427
34.477124
164
java
train-ticket
train-ticket-master/ts-verification-code-service/src/main/java/verifycode/util/CookieUtil.java
package verifycode.util; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * @author fdse */ public class CookieUtil { private CookieUtil() { throw new IllegalStateException("Utility class"); } public static void addCookie(HttpServletResponse response, String name, String value, int maxAge){ Cookie cookie = new Cookie(name,value); // against Cross-Site Scripting (XSS) attacks. cookie.setHttpOnly(true); cookie.setPath("/"); if(maxAge>0) { cookie.setMaxAge(maxAge); } response.addCookie(cookie); } public static Cookie getCookieByName(HttpServletRequest request, String name){ Map<String,Cookie> cookieMap = readCookieMap(request); return cookieMap.getOrDefault(name, null); } private static Map<String,Cookie> readCookieMap(HttpServletRequest request){ Map<String,Cookie> cookieMap = new HashMap<>(); Cookie[] cookies = request.getCookies(); if(null!=cookies){ for(Cookie cookie : cookies){ cookieMap.put(cookie.getName(), cookie); } } return cookieMap; } }
1,302
27.955556
102
java
train-ticket
train-ticket-master/ts-verification-code-service/src/test/java/verifycode/controller/VerifyCodeControllerTest.java
package verifycode.controller; import com.alibaba.fastjson.JSONObject; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpHeaders; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import verifycode.service.VerifyCodeService; import javax.servlet.*; import javax.servlet.http.*; import java.awt.image.BufferedImage; import java.io.*; import java.rmi.MarshalledObject; import java.security.Principal; import java.util.*; @RunWith(JUnit4.class) public class VerifyCodeControllerTest { @InjectMocks private VerifyCodeController verifyCodeController; @Mock private VerifyCodeService verifyCodeService; private MockMvc mockMvc; @Before public void setUp() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(verifyCodeController).build(); } @Test public void testImageCode() throws Exception { Map<String, Object> map = new HashMap<>(); BufferedImage image = new BufferedImage(60, 20, BufferedImage.TYPE_INT_RGB); map.put("strEnsure", "XYZ8"); map.put("image", image); Mockito.when(verifyCodeService.getImageCode(Mockito.anyInt(), Mockito.anyInt(), Mockito.any(OutputStream.class), Mockito.any(HttpServletRequest.class), Mockito.any(HttpServletResponse.class), Mockito.any(HttpHeaders.class))).thenReturn(map); mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/verifycode/generate")).andReturn(); Mockito.verify(verifyCodeService, Mockito.times(1)).getImageCode(Mockito.anyInt(), Mockito.anyInt(), Mockito.any(OutputStream.class), Mockito.any(HttpServletRequest.class), Mockito.any(HttpServletResponse.class), Mockito.any(HttpHeaders.class)); } @Test public void testVerifyCode() throws Exception { Mockito.when(verifyCodeService.verifyCode(Mockito.any(HttpServletRequest.class), Mockito.any(HttpServletResponse.class), Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(true); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/verifycode/verify/verifyCode")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertTrue(JSONObject.parseObject(result, Boolean.class)); } }
2,786
41.227273
253
java
train-ticket
train-ticket-master/ts-verification-code-service/src/test/java/verifycode/service/VerifyCodeServiceImplTest.java
package verifycode.service; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.springframework.http.HttpHeaders; import verifycode.service.impl.VerifyCodeServiceImpl; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.security.Principal; import java.util.Collection; import java.util.Enumeration; import java.util.Locale; import java.util.Map; @RunWith(JUnit4.class) public class VerifyCodeServiceImplTest { private VerifyCodeServiceImpl verifyCodeServiceImpl = new VerifyCodeServiceImpl(); private HttpHeaders headers = new HttpHeaders(); private HttpServletRequest request = new HttpServletRequest() { @Override public String getAuthType() { return null; } @Override public Cookie[] getCookies() { return new Cookie[0]; } @Override public long getDateHeader(String s) { return 0; } @Override public String getHeader(String s) { return null; } @Override public Enumeration<String> getHeaders(String s) { return null; } @Override public Enumeration<String> getHeaderNames() { return null; } @Override public int getIntHeader(String s) { return 0; } @Override public String getMethod() { return null; } @Override public String getPathInfo() { return null; } @Override public String getPathTranslated() { return null; } @Override public String getContextPath() { return null; } @Override public String getQueryString() { return null; } @Override public String getRemoteUser() { return null; } @Override public boolean isUserInRole(String s) { return false; } @Override public Principal getUserPrincipal() { return null; } @Override public String getRequestedSessionId() { return null; } @Override public String getRequestURI() { return null; } @Override public StringBuffer getRequestURL() { return null; } @Override public String getServletPath() { return null; } @Override public HttpSession getSession(boolean b) { return null; } @Override public HttpSession getSession() { return null; } @Override public String changeSessionId() { return null; } @Override public boolean isRequestedSessionIdValid() { return false; } @Override public boolean isRequestedSessionIdFromCookie() { return false; } @Override public boolean isRequestedSessionIdFromURL() { return false; } @Override public boolean isRequestedSessionIdFromUrl() { return false; } @Override public boolean authenticate(HttpServletResponse httpServletResponse) throws IOException, ServletException { return false; } @Override public void login(String s, String s1) throws ServletException { } @Override public void logout() throws ServletException { } @Override public Collection<Part> getParts() throws IOException, ServletException { return null; } @Override public Part getPart(String s) throws IOException, ServletException { return null; } @Override public <T extends HttpUpgradeHandler> T upgrade(Class<T> aClass) throws IOException, ServletException { return null; } @Override public Object getAttribute(String s) { return null; } @Override public Enumeration<String> getAttributeNames() { return null; } @Override public String getCharacterEncoding() { return null; } @Override public void setCharacterEncoding(String s) throws UnsupportedEncodingException { } @Override public int getContentLength() { return 0; } @Override public long getContentLengthLong() { return 0; } @Override public String getContentType() { return null; } @Override public ServletInputStream getInputStream() throws IOException { return null; } @Override public String getParameter(String s) { return null; } @Override public Enumeration<String> getParameterNames() { return null; } @Override public String[] getParameterValues(String s) { return new String[0]; } @Override public Map<String, String[]> getParameterMap() { return null; } @Override public String getProtocol() { return null; } @Override public String getScheme() { return null; } @Override public String getServerName() { return null; } @Override public int getServerPort() { return 0; } @Override public BufferedReader getReader() throws IOException { return null; } @Override public String getRemoteAddr() { return null; } @Override public String getRemoteHost() { return null; } @Override public void setAttribute(String s, Object o) { } @Override public void removeAttribute(String s) { } @Override public Locale getLocale() { return null; } @Override public Enumeration<Locale> getLocales() { return null; } @Override public boolean isSecure() { return false; } @Override public RequestDispatcher getRequestDispatcher(String s) { return null; } @Override public String getRealPath(String s) { return null; } @Override public int getRemotePort() { return 0; } @Override public String getLocalName() { return null; } @Override public String getLocalAddr() { return null; } @Override public int getLocalPort() { return 0; } @Override public ServletContext getServletContext() { return null; } @Override public AsyncContext startAsync() throws IllegalStateException { return null; } @Override public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException { return null; } @Override public boolean isAsyncStarted() { return false; } @Override public boolean isAsyncSupported() { return false; } @Override public AsyncContext getAsyncContext() { return null; } @Override public DispatcherType getDispatcherType() { return null; } }; private HttpServletResponse response = new HttpServletResponse() { @Override public void addCookie(Cookie cookie) { } @Override public boolean containsHeader(String s) { return false; } @Override public String encodeURL(String s) { return null; } @Override public String encodeRedirectURL(String s) { return null; } @Override public String encodeUrl(String s) { return null; } @Override public String encodeRedirectUrl(String s) { return null; } @Override public void sendError(int i, String s) throws IOException { } @Override public void sendError(int i) throws IOException { } @Override public void sendRedirect(String s) throws IOException { } @Override public void setDateHeader(String s, long l) { } @Override public void addDateHeader(String s, long l) { } @Override public void setHeader(String s, String s1) { } @Override public void addHeader(String s, String s1) { } @Override public void setIntHeader(String s, int i) { } @Override public void addIntHeader(String s, int i) { } @Override public void setStatus(int i) { } @Override public void setStatus(int i, String s) { } @Override public int getStatus() { return 0; } @Override public String getHeader(String s) { return null; } @Override public Collection<String> getHeaders(String s) { return null; } @Override public Collection<String> getHeaderNames() { return null; } @Override public String getCharacterEncoding() { return null; } @Override public String getContentType() { return null; } @Override public ServletOutputStream getOutputStream() throws IOException { return null; } @Override public PrintWriter getWriter() throws IOException { return null; } @Override public void setCharacterEncoding(String s) { } @Override public void setContentLength(int i) { } @Override public void setContentLengthLong(long l) { } @Override public void setContentType(String s) { } @Override public void setBufferSize(int i) { } @Override public int getBufferSize() { return 0; } @Override public void flushBuffer() throws IOException { } @Override public void resetBuffer() { } @Override public boolean isCommitted() { return false; } @Override public void reset() { } @Override public void setLocale(Locale locale) { } @Override public Locale getLocale() { return null; } }; @Test public void testGetImageCode() { OutputStream os = System.out; Map<String, Object> returnMap = verifyCodeServiceImpl.getImageCode(60, 20, os, request, response, headers); Assert.assertNotNull(returnMap); Assert.assertNotNull(returnMap.get("strEnsure")); } @Test public void testVerifyCode() { boolean result = verifyCodeServiceImpl.verifyCode(request, response, "XYZ5", headers); Assert.assertFalse(result); } }
11,802
19.598604
133
java
train-ticket
train-ticket-master/ts-wait-order-service/src/main/java/waitorder/WaitOrderApplication.java
package waitorder; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.web.client.RestTemplate; import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @EnableAspectJAutoProxy(proxyTargetClass = true) @EnableAsync @IntegrationComponentScan @EnableSwagger2 @EnableDiscoveryClient public class WaitOrderApplication { public static void main(String[] args) { SpringApplication.run(WaitOrderApplication.class, args); } @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
1,166
33.323529
75
java
train-ticket
train-ticket-master/ts-wait-order-service/src/main/java/waitorder/config/SecurityConfig.java
package waitorder.config; import edu.fudan.common.security.jwt.JWTFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import static org.springframework.web.cors.CorsConfiguration.ALL; /** * @author fdse */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { String admin = "ADMIN"; String order = "/api/v1/orderservice/order"; /** * load password encoder * * @return PasswordEncoder */ @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } /** * allow cors domain * header By default, only six fields can be taken from the header, and the other fields can only be specified in the header. * credentials Cookies are not sent by default and can only be true if a Cookie is needed * Validity of this request * * @return WebMvcConfigurer */ @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins(ALL) .allowedMethods(ALL) .allowedHeaders(ALL) .allowCredentials(false) .maxAge(3600); } }; } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.httpBasic().disable() // close default csrf .csrf().disable() // close session .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers(HttpMethod.POST, order).hasAnyRole(admin, "USER") .antMatchers(HttpMethod.PUT, order).hasAnyRole(admin, "USER") .antMatchers(HttpMethod.DELETE, order).hasAnyRole(admin, "USER") .antMatchers(HttpMethod.POST, "/api/v1/orderservice/order/admin").hasAnyRole(admin) .antMatchers(HttpMethod.PUT, "/api/v1/orderservice/order/admin").hasAnyRole(admin) .antMatchers("/api/v1/orderservice/order/**").permitAll() .antMatchers("/swagger-ui.html", "/webjars/**", "/images/**", "/configuration/**", "/swagger-resources/**", "/v2/**").permitAll() .anyRequest().authenticated() .and() .addFilterBefore(new JWTFilter(), UsernamePasswordAuthenticationFilter.class); // close cache httpSecurity.headers().cacheControl(); } }
3,799
40.758242
130
java
train-ticket
train-ticket-master/ts-wait-order-service/src/main/java/waitorder/controller/WaitListOrderController.java
package waitorder.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.*; import waitorder.entity.WaitListOrderVO; import waitorder.service.WaitListOrderService; import static org.springframework.http.ResponseEntity.ok; /** * @author fdse */ @RestController @RequestMapping("/api/v1/waitorderservice") public class WaitListOrderController { @Autowired private WaitListOrderService waitListOrderService; private static final Logger LOGGER = LoggerFactory.getLogger(WaitListOrderController.class); @GetMapping(path = "/welcome") public String home() { return "Welcome to [ Wait Order Service ] !"; } @PostMapping(path = "/order") public HttpEntity createNewOrder(@RequestBody WaitListOrderVO createOrder, @RequestHeader HttpHeaders headers) { WaitListOrderController.LOGGER.info("[createWaitOrder][Create Wait Order][from {} to {} at {}]", createOrder.getFrom(), createOrder.getTo(), createOrder.getDate()); return ok(waitListOrderService.create(createOrder, headers)); } @GetMapping(path = "/orders") public HttpEntity getAllOrders(@RequestHeader HttpHeaders headers){ LOGGER.info("[getAllOrders][Get All Orders]"); return ok(waitListOrderService.getAllOrders(headers)); } @GetMapping(path = "/waitlistorders") public HttpEntity getWaitListOrders(@RequestHeader HttpHeaders headers){ LOGGER.info("[getWaitListOrders][Get All Wait List Orders]"); return ok(waitListOrderService.getAllWaitListOrders(headers)); } }
1,758
32.188679
172
java
train-ticket
train-ticket-master/ts-wait-order-service/src/main/java/waitorder/entity/WaitListOrder.java
package waitorder.entity; import edu.fudan.common.util.StringUtils; import lombok.AllArgsConstructor; import lombok.Data; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.Calendar; import java.util.Date; @Data @AllArgsConstructor @Entity @GenericGenerator(name = "jpa-uuid", strategy ="uuid") public class WaitListOrder { @Id @GeneratedValue(generator = "jpa-uuid") @Column(length = 36) private String id; // private String travelDate; private String travelTime; @Column(length = 36) private String accountId; private String contactsId; private String contactsName; private int contactsDocumentType; private String contactsDocumentNumber; private String trainNumber; private int seatType; @Column(name = "from_station") private String from; @Column(name = "to_station") private String to; private String price; private String waitUtilTime; private String createdTime; private int status; public WaitListOrder(){ createdTime = StringUtils.Date2String(new Date(System.currentTimeMillis())); // trainNumber = "G1235"; // seatType = SeatClass.FIRSTCLASS.getCode(); // from = "shanghai"; // to = "taiyuan"; // price = "0.0"; //wait until 24 hours later Calendar c = Calendar.getInstance(); c.setTime(new Date(System.currentTimeMillis())); c.add(Calendar.DAY_OF_MONTH,1); waitUtilTime = StringUtils.Date2String(c.getTime()); travelTime=StringUtils.Date2String(c.getTime()); status= WaitListOrderStatus.NOTPAID.getCode(); } // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // WaitListOrder that = (WaitListOrder) o; // return contactsDocumentType == that.contactsDocumentType // && coachNumber == that.coachNumber // && seatClass == that.seatClass // && id.equals(that.id) // && Objects.equals(travelTime, that.travelTime) // && Objects.equals(accountId, that.accountId) // && Objects.equals(contactsName, that.contactsName) // && Objects.equals(contactsDocumentNumber, that.contactsDocumentNumber) // && Objects.equals(trainNumber, that.trainNumber) // && Objects.equals(seatNumber, that.seatNumber) // && Objects.equals(fromStation, that.fromStation) // && Objects.equals(toStation, that.toStation) // && Objects.equals(price, that.price); // } @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0 : id.hashCode()); return result; } public Date getCreatedTime(){ return StringUtils.String2Date(createdTime); } public Date getTravelTime(){ return StringUtils.String2Date(createdTime); } public Date getWaitUtilTime(){ return StringUtils.String2Date(waitUtilTime); } public void setCreatedTime(Date createdTime){ this.createdTime = StringUtils.Date2String(createdTime); } public void setTravelTime(Date travelTime){ this.createdTime = StringUtils.Date2String(travelTime); } public void setWaitUntilTime(Date waitUntilTime){ this.waitUtilTime=StringUtils.Date2String(waitUntilTime);} }
3,461
31.35514
112
java
train-ticket
train-ticket-master/ts-wait-order-service/src/main/java/waitorder/entity/WaitListOrderStatus.java
package waitorder.entity; import edu.fudan.common.entity.OrderStatus; public enum WaitListOrderStatus { /** * not paid */ NOTPAID (0,"Not Paid"), /** * paid and not collected */ PAID (1,"Paid & Not Collected"), /** * collected */ COLLECTED (2,"Collected"), /** * cancel */ CANCEL (3,"Cancel"), /** * refunded */ REFUNDS (4,"Refunded"), /** * expired */ EXPIRED (5, "Expired"); private int code; private String name; WaitListOrderStatus(int code, String name){ this.code = code; this.name = name; } public int getCode(){ return code; } public String getName() { return name; } public static String getNameByCode(int code){ OrderStatus[] orderStatusSet = OrderStatus.values(); for(OrderStatus orderStatus : orderStatusSet){ if(orderStatus.getCode() == code){ return orderStatus.getName(); } } return orderStatusSet[0].getName(); } }
1,106
17.762712
60
java
train-ticket
train-ticket-master/ts-wait-order-service/src/main/java/waitorder/entity/WaitListOrderVO.java
package waitorder.entity; import edu.fudan.common.util.StringUtils; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; /** * @author fdse */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class WaitListOrderVO { private String accountId; private String contactsId; private String tripId; private int seatType; private String date; private String from; private String to; private String price; public Date getDate(){ return StringUtils.String2Date(date); } public void setDate(Date date){ this.date = StringUtils.Date2String(date); } }
713
14.191489
50
java
train-ticket
train-ticket-master/ts-wait-order-service/src/main/java/waitorder/repository/WaitListOrderRepository.java
package waitorder.repository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import waitorder.entity.WaitListOrder; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Repository public interface WaitListOrderRepository extends CrudRepository<WaitListOrder,String> { @Override Optional<WaitListOrder> findById(String id); @Override List<WaitListOrder> findAll(); ArrayList<WaitListOrder> findByAccountId(String accountId); @Override void deleteById(String id); }
588
21.653846
87
java
train-ticket
train-ticket-master/ts-wait-order-service/src/main/java/waitorder/service/WaitListOrderService.java
package waitorder.service; import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; import waitorder.entity.WaitListOrder; import waitorder.entity.WaitListOrderVO; public interface WaitListOrderService { Response findOrderById(String id, HttpHeaders headers); Response create(WaitListOrderVO newOrder, HttpHeaders headers); /** * Get all orders, including completed and expired ones */ Response getAllOrders(HttpHeaders headers); Response updateOrder(WaitListOrder order, HttpHeaders headers); /** * Use when modifying order status */ Response modifyWaitListOrderStatus(int status, String orderId); /** * Get all orders in the wait list */ Response getAllWaitListOrders(HttpHeaders headers); }
795
24.677419
67
java
train-ticket
train-ticket-master/ts-wait-order-service/src/main/java/waitorder/service/Impl/WaitListOrderServiceImpl.java
package waitorder.service.Impl; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.RestTemplate; import waitorder.entity.WaitListOrder; import waitorder.entity.WaitListOrderStatus; import waitorder.entity.WaitListOrderVO; import waitorder.repository.WaitListOrderRepository; import waitorder.service.WaitListOrderService; import waitorder.utils.PollThread; import java.util.*; import java.util.stream.Collectors; @Service public class WaitListOrderServiceImpl implements WaitListOrderService { @Autowired private WaitListOrderRepository waitListOrderRepository; @Autowired private RestTemplate restTemplate; @Autowired private DiscoveryClient discoveryClient; private static final Logger LOGGER = LoggerFactory.getLogger(WaitListOrderServiceImpl.class); String success = "Success"; @Override public Response findOrderById(String id, HttpHeaders headers) { Optional<WaitListOrder> op = waitListOrderRepository.findById(id); if(!op.isPresent()){ LOGGER.warn("[findWaitOrderById][Find Order By Id Fail][No content][id: {}] ",id); return new Response<>(0, "No Content by this id", null); } else { WaitListOrder wo = op.get(); LOGGER.info("[findWaitOrderById][Find Order By Id Success][id: {}] ",id); return new Response<>(1, success, wo); } } @Transactional @Override public Response create(WaitListOrderVO orderVO, HttpHeaders headers) { LOGGER.info("[create][Create Wait Order][Ready to Create Wait Order]"); Response<WaitListOrder> response=saveNewOrder(orderVO,headers); if(response.getStatus()==0){ //未能正常保存到数据库 return response; } else { //已保存到数据库 开始轮询 return triggerThread(response.getData(),orderVO,headers); } } @Override public Response getAllOrders(HttpHeaders headers) { List<WaitListOrder> orderList= waitListOrderRepository.findAll(); if (orderList != null && !orderList.isEmpty()) { WaitListOrderServiceImpl.LOGGER.warn("[getAllOrders][Find all orders Success][size:{}]",orderList.size()); return new Response<>(1, "Success.", orderList); } else { LOGGER.warn("[getAllOrders][Find All Wait List Orders Fail][{}]","No content"); return new Response<>(0, "No Content.", null); } } @Override public Response getAllWaitListOrders(HttpHeaders headers) { List<WaitListOrder> orderList= waitListOrderRepository.findAll(); if (orderList != null && !orderList.isEmpty()) { WaitListOrderServiceImpl.LOGGER.warn("[getAllWaitListOrders][Find all orders Success][size:{}]",orderList.size()); List<Integer> filterList=new ArrayList<>(); filterList.add(WaitListOrderStatus.NOTPAID.getCode()); filterList.add(WaitListOrderStatus.PAID.getCode()); //Only orders in the wait list will be selected orderList=orderList.stream() .filter(WaitListOrder -> filterList.contains(WaitListOrder.getStatus())) .collect(Collectors.toList()); return new Response<>(1, "Success.", orderList); } else { LOGGER.warn("[getAllWaitListOrders][Find All Wait List Orders Fail][{}]","No content"); return new Response<>(0, "No Content.", null); } } @Transactional @Override public Response updateOrder(WaitListOrder order, HttpHeaders headers) { LOGGER.info("[updateOrder][Update Wait List Order][Order Info:{}] ", order.toString()); Optional<WaitListOrder> op = waitListOrderRepository.findById(order.getId()); if(!op.isPresent()){ LOGGER.error("[updateOrder][Update Order Info Fail][Order not found][OrderId: {}]",order.getId()); return new Response<>(0, "Order Not Found, Can't update", null); } else { WaitListOrder old = op.get(); BeanUtils.copyProperties(old,order); waitListOrderRepository.save(old); LOGGER.info("[updateOrder][Update Wait List Order Info Success][OrderId: {}]",order.getId()); return new Response<>(1, "Update Wait List Order Success", old); } } @Transactional @Override public Response modifyWaitListOrderStatus(int status, String orderId) { LOGGER.info("[modifyWaitListOrderStatus][Modify Order Status][OrderId:{}] ", orderId); Optional<WaitListOrder> op = waitListOrderRepository.findById(orderId); if(!op.isPresent()){ LOGGER.error("[modifyWaitListOrderStatus][Modify Order Status Fail][Order not found][OrderId: {}]",orderId); return new Response<>(0, "Order Not Found, Can't update", null); } else { WaitListOrder old = op.get(); old.setStatus(status); waitListOrderRepository.save(old); LOGGER.info("[modifyWaitListOrderStatus][Modify Order Status Success][OrderId: {}]",orderId); return new Response<>(1, "Modify Wait List Order Status Success", old); } } private Response<WaitListOrder> saveNewOrder(WaitListOrderVO orderVO, HttpHeaders headers) { ArrayList<WaitListOrder> accountOrders= waitListOrderRepository.findByAccountId(orderVO.getAccountId()); //if the order already exist if(WaitListOrderExist(accountOrders,orderVO)){ WaitListOrderServiceImpl.LOGGER.error("[create][Create Wait Order Fail][Order already exists][AccountId: {} , TripId: {}]", orderVO.getAccountId(),orderVO.getTripId()); return new Response<>(0, "Order already exist", null); } else { WaitListOrder newWaitListOrder=new WaitListOrder(); newWaitListOrder.setId(UUID.randomUUID().toString()); BeanUtils.copyProperties(newWaitListOrder,orderVO); newWaitListOrder.setTrainNumber(orderVO.getTripId()); waitListOrderRepository.save(newWaitListOrder); WaitListOrderServiceImpl.LOGGER.info("[create][Create Wait Order Success][Order Price][AccountId: {} , TripId: {}]", orderVO.getAccountId(),orderVO.getTripId()); return new Response<>(1,success,newWaitListOrder); } } private Boolean WaitListOrderExist(List<WaitListOrder> orderList,WaitListOrderVO newOrder){ for(WaitListOrder order: orderList){ if(Objects.equals(order.getAccountId(), newOrder.getAccountId()) && Objects.equals(order.getContactsId(), newOrder.getContactsId()) && Objects.equals(order.getTrainNumber(), newOrder.getTripId()) && Objects.equals(order.getTravelTime(),newOrder.getDate()) && Objects.equals(order.getFrom(),newOrder.getFrom()) && Objects.equals(order.getTo(),newOrder.getTo())){ return true; } } return false; } private Response triggerThread(WaitListOrder orderPO,WaitListOrderVO orderVO,HttpHeaders headers){ PollThread pollThread; try{ pollThread =new PollThread(orderPO.getWaitUtilTime(),this,orderVO,restTemplate, headers); pollThread.start(); } catch (Exception e){ return new Response<>(0, "Fail To Run A New Thread", null); } return new Response<>(1,"Thread Start Success",null); } }
7,895
44.12
180
java
train-ticket
train-ticket-master/ts-wait-order-service/src/main/java/waitorder/utils/PollThread.java
package waitorder.utils; import edu.fudan.common.entity.Contacts; import edu.fudan.common.util.Response; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import waitorder.entity.WaitListOrderStatus; import waitorder.entity.WaitListOrderVO; import waitorder.service.WaitListOrderService; import java.util.Date; import java.util.concurrent.TimeUnit; public class PollThread extends Thread{ private Date waitUntil; private WaitListOrderVO waitListOrderVO; private HttpHeaders httpHeaders; private RestTemplate restTemplate; private WaitListOrderService waitListOrderService; final static Integer INTERVAL_MINUTES=5; public PollThread(Date waitUntilTime,WaitListOrderService service, WaitListOrderVO order, RestTemplate template, HttpHeaders headers){ restTemplate=template; httpHeaders=headers; waitListOrderVO=order; waitListOrderService =service; waitUntil=waitUntilTime; } @Override public void run() { String service_url=getServiceUrl("ts-preserve-service"); HttpEntity requestEntityPreserve = new HttpEntity(waitListOrderVO,httpHeaders); //TODO compare with waitUntilTime while(true){ long currentTime=System.currentTimeMillis(); if(waitUntil.getTime()>currentTime){ // expired waitListOrderService.modifyWaitListOrderStatus(WaitListOrderStatus.EXPIRED.getCode(), waitListOrderVO.getAccountId()); break; } Response postResult=doPreserve(service_url,requestEntityPreserve); if(postResult.getStatus()==0){ //预定失败 try { TimeUnit.MINUTES.sleep(INTERVAL_MINUTES); } catch (InterruptedException e) { e.printStackTrace(); } } else{ // preserve success waitListOrderService.modifyWaitListOrderStatus(WaitListOrderStatus.COLLECTED.getCode(),waitListOrderVO.getAccountId()); break; } } } private String getServiceUrl(String serviceName) { return "http://" + serviceName; } private Response doPreserve(String url, HttpEntity requestParam){ ResponseEntity<Response<Contacts>> rePostPreserveResult = restTemplate.exchange( url + "/api/v1/contactservice/preserve", HttpMethod.POST, requestParam, new ParameterizedTypeReference<Response<Contacts>>() { }); return rePostPreserveResult.getBody(); } }
2,874
32.823529
138
java
train-ticket
train-ticket-master/ts-wait-order-service/src/test/java/waitorder/WaitOrderApplicationTests.java
package waitorder; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class WaitOrderApplicationTests { @Test void contextLoads() { } }
213
14.285714
60
java
train-ticket
train-ticket-master/ts-wait-order-service/src/test/java/waitorder/service/Impl/WaitListOrderServiceImplTest.java
package waitorder.service.Impl; import java.util.Optional; import edu.fudan.common.util.Response; import org.junit.Before; import org.junit.BeforeClass; import org.junit.jupiter.api.Assertions; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpHeaders; import waitorder.entity.WaitListOrder; import waitorder.repository.WaitListOrderRepository; @RunWith(JUnit4.class) public class WaitListOrderServiceImplTest { @InjectMocks private WaitListOrderServiceImpl waitListOrderServiceImpl; @Mock private WaitListOrderRepository repository; private HttpHeaders headers = new HttpHeaders(); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void findOrderById() { Mockito.when(repository.findById(Mockito.any(String.class))).thenReturn(Optional.ofNullable(null)); Response response=waitListOrderServiceImpl.findOrderById("id",headers); Assertions.assertEquals(new Response<>(0, "No Content by this id", null), response); } @Test public void getAllOrders() { Mockito.when(repository.findAll()).thenReturn(null); Response res = waitListOrderServiceImpl.getAllOrders(headers); Assertions.assertEquals(new Response<>(0,"No Content.",null),res); } }
1,490
27.673077
107
java
yuck
yuck-master/src/main/yuck/util/alg/rtree/RTreeTransaction.java
package yuck.util.alg.rtree; import com.conversantmedia.util.collection.spatial.HyperRect; import com.conversantmedia.util.collection.spatial.RectBuilder; import com.conversantmedia.util.collection.spatial.SpatialSearch; import com.conversantmedia.util.collection.spatial.Stats; import java.util.Collection; import java.util.HashSet; import java.util.function.Consumer; /** * Facilitates the simulation of small changes to a given R tree. * * @author Michael Marte */ final public class RTreeTransaction<T> implements SpatialSearch<T> { final SpatialSearch<T> rTree; final RectBuilder<T> builder; final HashSet<T> added = new HashSet<T>(); final HashSet<T> removed = new HashSet<T>(); public RTreeTransaction(final SpatialSearch<T> rTree, final RectBuilder<T> builder) { this.rTree = rTree; this.builder = builder; } @Override public int intersects(final HyperRect rect, final T[] t) { throw new UnsupportedOperationException(); } @Override public void intersects(final HyperRect rect, final Consumer<T> consumer) { for (final T t : added) { if (rect.intersects(builder.getBBox(t))) { consumer.accept(t); } } rTree.intersects( rect, new Consumer<T>() { @Override public void accept(final T t) { if (! removed.contains(t)) { consumer.accept(t); } } }); } @Override public int search(final HyperRect rect, final T[] t) { throw new UnsupportedOperationException(); } @Override public void search(final HyperRect rect, final Consumer<T> consumer) { throw new UnsupportedOperationException(); } @Override public void search(final HyperRect rect, final Collection<T> collection) { throw new UnsupportedOperationException(); } @Override public boolean contains(final T t) { throw new UnsupportedOperationException(); } @Override public void add(final T t) { if (! removed.remove(t)) { added.add(t); } } @Override public void remove(final T t) { if (! added.remove(t)) { removed.add(t); } } @Override public void update(final T t1, final T t2) { remove(t1); add(t2); } @Override public void forEach(final Consumer<T> consumer) { for (final T t : added) { consumer.accept(t); } rTree.forEach( new Consumer<T>() { @Override public void accept(final T t) { if (! removed.contains(t)) { consumer.accept(t); } } }); } @Override public int getEntryCount() { throw new UnsupportedOperationException(); } @Override public Stats collectStats() { throw new UnsupportedOperationException(); } public void rollback() { added.clear(); removed.clear(); } public void commit() { for (final T t: removed) { rTree.remove(t); } removed.clear(); for (final T t: added) { rTree.add(t); } added.clear(); } }
3,403
24.029412
89
java
z3
z3-master/examples/java/JavaExample.java
/*++ Copyright (c) 2012 Microsoft Corporation Module Name: Program.java Abstract: Z3 Java API: Example program Author: Christoph Wintersteiger (cwinter) 2012-11-27 Notes: --*/ import java.util.*; import com.microsoft.z3.*; class JavaExample { @SuppressWarnings("serial") class TestFailedException extends Exception { public TestFailedException() { super("Check FAILED"); } }; // / Create axiom: function f is injective in the i-th argument. // / <remarks> // / The following axiom is produced: // / <code> // / forall (x_0, ..., x_n) finv(f(x_0, ..., x_i, ..., x_{n-1})) = x_i // / </code> // / Where, <code>finv</code>is a fresh function declaration. public BoolExpr injAxiom(Context ctx, FuncDecl f, int i) { Sort[] domain = f.getDomain(); int sz = f.getDomainSize(); if (i >= sz) { System.out.println("failed to create inj axiom"); return null; } /* declare the i-th inverse of f: finv */ Sort finv_domain = f.getRange(); Sort finv_range = domain[i]; FuncDecl finv = ctx.mkFuncDecl("f_fresh", finv_domain, finv_range); /* allocate temporary arrays */ Expr[] xs = new Expr[sz]; Symbol[] names = new Symbol[sz]; Sort[] types = new Sort[sz]; /* fill types, names and xs */ for (int j = 0; j < sz; j++) { types[j] = domain[j]; names[j] = ctx.mkSymbol("x_" + Integer.toString(j)); xs[j] = ctx.mkBound(j, types[j]); } Expr x_i = xs[i]; /* create f(x_0, ..., x_i, ..., x_{n-1}) */ Expr fxs = f.apply(xs); /* create f_inv(f(x_0, ..., x_i, ..., x_{n-1})) */ Expr finv_fxs = finv.apply(fxs); /* create finv(f(x_0, ..., x_i, ..., x_{n-1})) = x_i */ Expr eq = ctx.mkEq(finv_fxs, x_i); /* use f(x_0, ..., x_i, ..., x_{n-1}) as the pattern for the quantifier */ Pattern p = ctx.mkPattern(fxs); /* create & assert quantifier */ BoolExpr q = ctx.mkForall(types, /* types of quantified variables */ names, /* names of quantified variables */ eq, 1, new Pattern[] { p } /* patterns */, null, null, null); return q; } // / Create axiom: function f is injective in the i-th argument. // / <remarks> // / The following axiom is produced: // / <code> // / forall (x_0, ..., x_n) finv(f(x_0, ..., x_i, ..., x_{n-1})) = x_i // / </code> // / Where, <code>finv</code>is a fresh function declaration. public BoolExpr injAxiomAbs(Context ctx, FuncDecl f, int i) { Sort[] domain = f.getDomain(); int sz = f.getDomainSize(); if (i >= sz) { System.out.println("failed to create inj axiom"); return null; } /* declare the i-th inverse of f: finv */ Sort finv_domain = f.getRange(); Sort finv_range = domain[i]; FuncDecl finv = ctx.mkFuncDecl("f_fresh", finv_domain, finv_range); /* allocate temporary arrays */ Expr[] xs = new Expr[sz]; /* fill types, names and xs */ for (int j = 0; j < sz; j++) { xs[j] = ctx.mkConst("x_" + Integer.toString(j), domain[j]); } Expr x_i = xs[i]; /* create f(x_0, ..., x_i, ..., x_{n-1}) */ Expr fxs = f.apply(xs); /* create f_inv(f(x_0, ..., x_i, ..., x_{n-1})) */ Expr finv_fxs = finv.apply(fxs); /* create finv(f(x_0, ..., x_i, ..., x_{n-1})) = x_i */ Expr eq = ctx.mkEq(finv_fxs, x_i); /* use f(x_0, ..., x_i, ..., x_{n-1}) as the pattern for the quantifier */ Pattern p = ctx.mkPattern(fxs); /* create & assert quantifier */ BoolExpr q = ctx.mkForall(xs, /* types of quantified variables */ eq, /* names of quantified variables */ 1, new Pattern[] { p } /* patterns */, null, null, null); return q; } // / Assert the axiom: function f is commutative. // / <remarks> // / This example uses the SMT-LIB parser to simplify the axiom // construction. // / </remarks> private BoolExpr commAxiom(Context ctx, FuncDecl f) throws Exception { Sort t = f.getRange(); Sort[] dom = f.getDomain(); if (dom.length != 2 || !t.equals(dom[0]) || !t.equals(dom[1])) { System.out.println(Integer.toString(dom.length) + " " + dom[0].toString() + " " + dom[1].toString() + " " + t.toString()); throw new Exception( "function must be binary, and argument types must be equal to return type"); } String bench = "(assert (forall (x " + t.getName() + ") (y " + t.getName() + ") (= (" + f.getName() + " x y) (" + f.getName() + " y x))))"; return ctx.parseSMTLIB2String(bench, new Symbol[] { t.getName() }, new Sort[] { t }, new Symbol[] { f.getName() }, new FuncDecl[] { f })[0]; } // / "Hello world" example: create a Z3 logical context, and delete it. public void simpleExample() { System.out.println("SimpleExample"); Log.append("SimpleExample"); { Context ctx = new Context(); /* do something with the context */ /* be kind to dispose manually and not wait for the GC. */ ctx.close(); } } Model check(Context ctx, BoolExpr f, Status sat) throws TestFailedException { Solver s = ctx.mkSolver(); s.add(f); if (s.check() != sat) throw new TestFailedException(); if (sat == Status.SATISFIABLE) return s.getModel(); else return null; } void solveTactical(Context ctx, Tactic t, Goal g, Status sat) throws TestFailedException { Solver s = ctx.mkSolver(t); System.out.println("\nTactical solver: " + s); for (BoolExpr a : g.getFormulas()) s.add(a); System.out.println("Solver: " + s); if (s.check() != sat) throw new TestFailedException(); } ApplyResult applyTactic(Context ctx, Tactic t, Goal g) { System.out.println("\nGoal: " + g); ApplyResult res = t.apply(g); System.out.println("Application result: " + res); Status q = Status.UNKNOWN; for (Goal sg : res.getSubgoals()) if (sg.isDecidedSat()) q = Status.SATISFIABLE; else if (sg.isDecidedUnsat()) q = Status.UNSATISFIABLE; switch (q) { case UNKNOWN: System.out.println("Tactic result: Undecided"); break; case SATISFIABLE: System.out.println("Tactic result: SAT"); break; case UNSATISFIABLE: System.out.println("Tactic result: UNSAT"); break; } return res; } void prove(Context ctx, BoolExpr f, boolean useMBQI) throws TestFailedException { BoolExpr[] assumptions = new BoolExpr[0]; prove(ctx, f, useMBQI, assumptions); } void prove(Context ctx, BoolExpr f, boolean useMBQI, BoolExpr... assumptions) throws TestFailedException { System.out.println("Proving: " + f); Solver s = ctx.mkSolver(); Params p = ctx.mkParams(); p.add("mbqi", useMBQI); s.setParameters(p); for (BoolExpr a : assumptions) s.add(a); s.add(ctx.mkNot(f)); Status q = s.check(); switch (q) { case UNKNOWN: System.out.println("Unknown because: " + s.getReasonUnknown()); break; case SATISFIABLE: throw new TestFailedException(); case UNSATISFIABLE: System.out.println("OK, proof: " + s.getProof()); break; } } void disprove(Context ctx, BoolExpr f, boolean useMBQI) throws TestFailedException { BoolExpr[] a = {}; disprove(ctx, f, useMBQI, a); } void disprove(Context ctx, BoolExpr f, boolean useMBQI, BoolExpr... assumptions) throws TestFailedException { System.out.println("Disproving: " + f); Solver s = ctx.mkSolver(); Params p = ctx.mkParams(); p.add("mbqi", useMBQI); s.setParameters(p); for (BoolExpr a : assumptions) s.add(a); s.add(ctx.mkNot(f)); Status q = s.check(); switch (q) { case UNKNOWN: System.out.println("Unknown because: " + s.getReasonUnknown()); break; case SATISFIABLE: System.out.println("OK, model: " + s.getModel()); break; case UNSATISFIABLE: throw new TestFailedException(); } } void modelConverterTest(Context ctx) throws TestFailedException { System.out.println("ModelConverterTest"); ArithExpr xr = (ArithExpr) ctx.mkConst(ctx.mkSymbol("x"), ctx.mkRealSort()); ArithExpr yr = (ArithExpr) ctx.mkConst(ctx.mkSymbol("y"), ctx.mkRealSort()); Goal g4 = ctx.mkGoal(true, false, false); g4.add(ctx.mkGt(xr, ctx.mkReal(10, 1))); g4.add(ctx.mkEq(yr, ctx.mkAdd(xr, ctx.mkReal(1, 1)))); g4.add(ctx.mkGt(yr, ctx.mkReal(1, 1))); ApplyResult ar = applyTactic(ctx, ctx.mkTactic("simplify"), g4); if (ar.getNumSubgoals() == 1 && (ar.getSubgoals()[0].isDecidedSat() || ar.getSubgoals()[0] .isDecidedUnsat())) throw new TestFailedException(); ar = applyTactic(ctx, ctx.andThen(ctx.mkTactic("simplify"), ctx.mkTactic("solve-eqs")), g4); if (ar.getNumSubgoals() == 1 && (ar.getSubgoals()[0].isDecidedSat() || ar.getSubgoals()[0] .isDecidedUnsat())) throw new TestFailedException(); Solver s = ctx.mkSolver(); for (BoolExpr e : ar.getSubgoals()[0].getFormulas()) s.add(e); Status q = s.check(); System.out.println("Solver says: " + q); System.out.println("Model: \n" + s.getModel()); if (q != Status.SATISFIABLE) throw new TestFailedException(); } // / A simple array example. void arrayExample1(Context ctx) throws TestFailedException { System.out.println("ArrayExample1"); Log.append("ArrayExample1"); Goal g = ctx.mkGoal(true, false, false); ArraySort asort = ctx.mkArraySort(ctx.getIntSort(), ctx.mkBitVecSort(32)); ArrayExpr aex = (ArrayExpr) ctx.mkConst(ctx.mkSymbol("MyArray"), asort); Expr sel = ctx.mkSelect(aex, ctx.mkInt(0)); g.add(ctx.mkEq(sel, ctx.mkBV(42, 32))); Symbol xs = ctx.mkSymbol("x"); IntExpr xc = (IntExpr) ctx.mkConst(xs, ctx.getIntSort()); Symbol fname = ctx.mkSymbol("f"); Sort[] domain = { ctx.getIntSort() }; FuncDecl fd = ctx.mkFuncDecl(fname, domain, ctx.getIntSort()); Expr[] fargs = { ctx.mkConst(xs, ctx.getIntSort()) }; IntExpr fapp = (IntExpr) ctx.mkApp(fd, fargs); g.add(ctx.mkEq(ctx.mkAdd(xc, fapp), ctx.mkInt(123))); Solver s = ctx.mkSolver(); for (BoolExpr a : g.getFormulas()) s.add(a); System.out.println("Solver: " + s); Status q = s.check(); System.out.println("Status: " + q); if (q != Status.SATISFIABLE) throw new TestFailedException(); System.out.println("Model = " + s.getModel()); System.out.println("Interpretation of MyArray:\n" + s.getModel().getFuncInterp(aex.getFuncDecl())); System.out.println("Interpretation of x:\n" + s.getModel().getConstInterp(xc)); System.out.println("Interpretation of f:\n" + s.getModel().getFuncInterp(fd)); System.out.println("Interpretation of MyArray as Term:\n" + s.getModel().getFuncInterp(aex.getFuncDecl())); } // / Prove <tt>store(a1, i1, v1) = store(a2, i2, v2) implies (i1 = i3 or i2 // = i3 or select(a1, i3) = select(a2, i3))</tt>. // / <remarks>This example demonstrates how to use the array // theory.</remarks> public void arrayExample2(Context ctx) throws TestFailedException { System.out.println("ArrayExample2"); Log.append("ArrayExample2"); Sort int_type = ctx.getIntSort(); Sort array_type = ctx.mkArraySort(int_type, int_type); ArrayExpr a1 = (ArrayExpr) ctx.mkConst("a1", array_type); ArrayExpr a2 = ctx.mkArrayConst("a2", int_type, int_type); Expr i1 = ctx.mkConst("i1", int_type); Expr i2 = ctx.mkConst("i2", int_type); Expr i3 = ctx.mkConst("i3", int_type); Expr v1 = ctx.mkConst("v1", int_type); Expr v2 = ctx.mkConst("v2", int_type); Expr st1 = ctx.mkStore(a1, i1, v1); Expr st2 = ctx.mkStore(a2, i2, v2); Expr sel1 = ctx.mkSelect(a1, i3); Expr sel2 = ctx.mkSelect(a2, i3); /* create antecedent */ BoolExpr antecedent = ctx.mkEq(st1, st2); /* * create consequent: i1 = i3 or i2 = i3 or select(a1, i3) = select(a2, * i3) */ BoolExpr consequent = ctx.mkOr(ctx.mkEq(i1, i3), ctx.mkEq(i2, i3), ctx.mkEq(sel1, sel2)); /* * prove store(a1, i1, v1) = store(a2, i2, v2) implies (i1 = i3 or i2 = * i3 or select(a1, i3) = select(a2, i3)) */ BoolExpr thm = ctx.mkImplies(antecedent, consequent); System.out .println("prove: store(a1, i1, v1) = store(a2, i2, v2) implies (i1 = i3 or i2 = i3 or select(a1, i3) = select(a2, i3))"); System.out.println(thm); prove(ctx, thm, false); } // / Show that <code>distinct(a_0, ... , a_n)</code> is // / unsatisfiable when <code>a_i</code>'s are arrays from boolean to // / boolean and n > 4. // / <remarks>This example also shows how to use the <code>distinct</code> // construct.</remarks> public void arrayExample3(Context ctx) throws TestFailedException { System.out.println("ArrayExample3"); Log.append("ArrayExample2"); for (int n = 2; n <= 5; n++) { System.out.println("n = " + Integer.toString(n)); Sort bool_type = ctx.mkBoolSort(); Sort array_type = ctx.mkArraySort(bool_type, bool_type); Expr[] a = new Expr[n]; /* create arrays */ for (int i = 0; i < n; i++) { a[i] = ctx.mkConst("array_" + Integer.toString(i), array_type); } /* assert distinct(a[0], ..., a[n]) */ BoolExpr d = ctx.mkDistinct(a); System.out.println(d); /* context is satisfiable if n < 5 */ Model model = check(ctx, d, n < 5 ? Status.SATISFIABLE : Status.UNSATISFIABLE); if (n < 5) { for (int i = 0; i < n; i++) { System.out.println(a[i].toString() + " = " + model.evaluate(a[i], false)); } } } } // / Sudoku solving example. void sudokuExample(Context ctx) throws TestFailedException { System.out.println("SudokuExample"); Log.append("SudokuExample"); // 9x9 matrix of integer variables IntExpr[][] X = new IntExpr[9][]; for (int i = 0; i < 9; i++) { X[i] = new IntExpr[9]; for (int j = 0; j < 9; j++) X[i][j] = (IntExpr) ctx.mkConst( ctx.mkSymbol("x_" + (i + 1) + "_" + (j + 1)), ctx.getIntSort()); } // each cell contains a value in {1, ..., 9} BoolExpr[][] cells_c = new BoolExpr[9][]; for (int i = 0; i < 9; i++) { cells_c[i] = new BoolExpr[9]; for (int j = 0; j < 9; j++) cells_c[i][j] = ctx.mkAnd(ctx.mkLe(ctx.mkInt(1), X[i][j]), ctx.mkLe(X[i][j], ctx.mkInt(9))); } // each row contains a digit at most once BoolExpr[] rows_c = new BoolExpr[9]; for (int i = 0; i < 9; i++) rows_c[i] = ctx.mkDistinct(X[i]); // each column contains a digit at most once BoolExpr[] cols_c = new BoolExpr[9]; for (int j = 0; j < 9; j++) { IntExpr[] col = new IntExpr[9]; for (int i = 0; i < 9; i++) { col[i] = X[i][j]; } cols_c[j] = ctx.mkDistinct(col); } // each 3x3 square contains a digit at most once BoolExpr[][] sq_c = new BoolExpr[3][]; for (int i0 = 0; i0 < 3; i0++) { sq_c[i0] = new BoolExpr[3]; for (int j0 = 0; j0 < 3; j0++) { IntExpr[] square = new IntExpr[9]; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) square[3 * i + j] = X[3 * i0 + i][3 * j0 + j]; sq_c[i0][j0] = ctx.mkDistinct(square); } } BoolExpr sudoku_c = ctx.mkTrue(); for (BoolExpr[] t : cells_c) sudoku_c = ctx.mkAnd(ctx.mkAnd(t), sudoku_c); sudoku_c = ctx.mkAnd(ctx.mkAnd(rows_c), sudoku_c); sudoku_c = ctx.mkAnd(ctx.mkAnd(cols_c), sudoku_c); for (BoolExpr[] t : sq_c) sudoku_c = ctx.mkAnd(ctx.mkAnd(t), sudoku_c); // sudoku instance, we use '0' for empty cells int[][] instance = { { 0, 0, 0, 0, 9, 4, 0, 3, 0 }, { 0, 0, 0, 5, 1, 0, 0, 0, 7 }, { 0, 8, 9, 0, 0, 0, 0, 4, 0 }, { 0, 0, 0, 0, 0, 0, 2, 0, 8 }, { 0, 6, 0, 2, 0, 1, 0, 5, 0 }, { 1, 0, 2, 0, 0, 0, 0, 0, 0 }, { 0, 7, 0, 0, 0, 0, 5, 2, 0 }, { 9, 0, 0, 0, 6, 5, 0, 0, 0 }, { 0, 4, 0, 9, 7, 0, 0, 0, 0 } }; BoolExpr instance_c = ctx.mkTrue(); for (int i = 0; i < 9; i++) for (int j = 0; j < 9; j++) if (0 != instance[i][j]) instance_c = ctx.mkAnd( instance_c, ctx.mkEq(X[i][j], ctx.mkInt(instance[i][j]))); Solver s = ctx.mkSolver(); s.add(sudoku_c); s.add(instance_c); if (s.check() == Status.SATISFIABLE) { Model m = s.getModel(); Expr[][] R = new Expr[9][9]; for (int i = 0; i < 9; i++) for (int j = 0; j < 9; j++) R[i][j] = m.evaluate(X[i][j], false); System.out.println("Sudoku solution:"); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) System.out.print(" " + R[i][j]); System.out.println(); } } else { System.out.println("Failed to solve sudoku"); throw new TestFailedException(); } } // / A basic example of how to use quantifiers. void quantifierExample1(Context ctx) { System.out.println("QuantifierExample"); Log.append("QuantifierExample"); IntSort[] types = new IntSort[3]; IntExpr[] xs = new IntExpr[3]; Symbol[] names = new Symbol[3]; IntExpr[] vars = new IntExpr[3]; for (int j = 0; j < 3; j++) { types[j] = ctx.getIntSort(); names[j] = ctx.mkSymbol("x_" + Integer.toString(j)); xs[j] = (IntExpr) ctx.mkConst(names[j], types[j]); vars[j] = (IntExpr) ctx.mkBound(2 - j, types[j]); // <-- vars // reversed! } Expr body_vars = ctx.mkAnd( ctx.mkEq(ctx.mkAdd(vars[0], ctx.mkInt(1)), ctx.mkInt(2)), ctx.mkEq(ctx.mkAdd(vars[1], ctx.mkInt(2)), ctx.mkAdd(vars[2], ctx.mkInt(3)))); Expr body_const = ctx.mkAnd( ctx.mkEq(ctx.mkAdd(xs[0], ctx.mkInt(1)), ctx.mkInt(2)), ctx.mkEq(ctx.mkAdd(xs[1], ctx.mkInt(2)), ctx.mkAdd(xs[2], ctx.mkInt(3)))); Expr x = ctx.mkForall(types, names, body_vars, 1, null, null, ctx.mkSymbol("Q1"), ctx.mkSymbol("skid1")); System.out.println("Quantifier X: " + x.toString()); Expr y = ctx.mkForall(xs, body_const, 1, null, null, ctx.mkSymbol("Q2"), ctx.mkSymbol("skid2")); System.out.println("Quantifier Y: " + y.toString()); } void quantifierExample2(Context ctx) { System.out.println("QuantifierExample2"); Log.append("QuantifierExample2"); Expr q1, q2; FuncDecl f = ctx.mkFuncDecl("f", ctx.getIntSort(), ctx.getIntSort()); FuncDecl g = ctx.mkFuncDecl("g", ctx.getIntSort(), ctx.getIntSort()); // Quantifier with Exprs as the bound variables. { Expr x = ctx.mkConst("x", ctx.getIntSort()); Expr y = ctx.mkConst("y", ctx.getIntSort()); Expr f_x = ctx.mkApp(f, x); Expr f_y = ctx.mkApp(f, y); Expr g_y = ctx.mkApp(g, y); @SuppressWarnings("unused") Pattern[] pats = new Pattern[] { ctx.mkPattern(f_x, g_y) }; Expr[] no_pats = new Expr[] { f_y }; Expr[] bound = new Expr[] { x, y }; Expr body = ctx.mkAnd(ctx.mkEq(f_x, f_y), ctx.mkEq(f_y, g_y)); q1 = ctx.mkForall(bound, body, 1, null, no_pats, ctx.mkSymbol("q"), ctx.mkSymbol("sk")); System.out.println(q1); } // Quantifier with de-Bruijn indices. { Expr x = ctx.mkBound(1, ctx.getIntSort()); Expr y = ctx.mkBound(0, ctx.getIntSort()); Expr f_x = ctx.mkApp(f, x); Expr f_y = ctx.mkApp(f, y); Expr g_y = ctx.mkApp(g, y); @SuppressWarnings("unused") Pattern[] pats = new Pattern[] { ctx.mkPattern(f_x, g_y) }; Expr[] no_pats = new Expr[] { f_y }; Symbol[] names = new Symbol[] { ctx.mkSymbol("x"), ctx.mkSymbol("y") }; Sort[] sorts = new Sort[] { ctx.getIntSort(), ctx.getIntSort() }; Expr body = ctx.mkAnd(ctx.mkEq(f_x, f_y), ctx.mkEq(f_y, g_y)); q2 = ctx.mkForall(sorts, names, body, 1, null, // pats, no_pats, ctx.mkSymbol("q"), ctx.mkSymbol("sk")); System.out.println(q2); } System.out.println(q1.equals(q2)); } // / Prove that <tt>f(x, y) = f(w, v) implies y = v</tt> when // / <code>f</code> is injective in the second argument. <seealso // cref="inj_axiom"/> public void quantifierExample3(Context ctx) throws TestFailedException { System.out.println("QuantifierExample3"); Log.append("QuantifierExample3"); /* * If quantified formulas are asserted in a logical context, then the * model produced by Z3 should be viewed as a potential model. */ /* declare function f */ Sort I = ctx.getIntSort(); FuncDecl f = ctx.mkFuncDecl("f", new Sort[] { I, I }, I); /* f is injective in the second argument. */ BoolExpr inj = injAxiom(ctx, f, 1); /* create x, y, v, w, fxy, fwv */ Expr x = ctx.mkIntConst("x"); Expr y = ctx.mkIntConst("y"); Expr v = ctx.mkIntConst("v"); Expr w = ctx.mkIntConst("w"); Expr fxy = ctx.mkApp(f, x, y); Expr fwv = ctx.mkApp(f, w, v); /* f(x, y) = f(w, v) */ BoolExpr p1 = ctx.mkEq(fxy, fwv); /* prove f(x, y) = f(w, v) implies y = v */ BoolExpr p2 = ctx.mkEq(y, v); prove(ctx, p2, false, inj, p1); /* disprove f(x, y) = f(w, v) implies x = w */ BoolExpr p3 = ctx.mkEq(x, w); disprove(ctx, p3, false, inj, p1); } // / Prove that <tt>f(x, y) = f(w, v) implies y = v</tt> when // / <code>f</code> is injective in the second argument. <seealso // cref="inj_axiom"/> public void quantifierExample4(Context ctx) throws TestFailedException { System.out.println("QuantifierExample4"); Log.append("QuantifierExample4"); /* * If quantified formulas are asserted in a logical context, then the * model produced by Z3 should be viewed as a potential model. */ /* declare function f */ Sort I = ctx.getIntSort(); FuncDecl f = ctx.mkFuncDecl("f", new Sort[] { I, I }, I); /* f is injective in the second argument. */ BoolExpr inj = injAxiomAbs(ctx, f, 1); /* create x, y, v, w, fxy, fwv */ Expr x = ctx.mkIntConst("x"); Expr y = ctx.mkIntConst("y"); Expr v = ctx.mkIntConst("v"); Expr w = ctx.mkIntConst("w"); Expr fxy = ctx.mkApp(f, x, y); Expr fwv = ctx.mkApp(f, w, v); /* f(x, y) = f(w, v) */ BoolExpr p1 = ctx.mkEq(fxy, fwv); /* prove f(x, y) = f(w, v) implies y = v */ BoolExpr p2 = ctx.mkEq(y, v); prove(ctx, p2, false, inj, p1); /* disprove f(x, y) = f(w, v) implies x = w */ BoolExpr p3 = ctx.mkEq(x, w); disprove(ctx, p3, false, inj, p1); } // / Some basic tests. void basicTests(Context ctx) throws TestFailedException { System.out.println("BasicTests"); Symbol fname = ctx.mkSymbol("f"); Symbol x = ctx.mkSymbol("x"); Symbol y = ctx.mkSymbol("y"); Sort bs = ctx.mkBoolSort(); Sort[] domain = { bs, bs }; FuncDecl f = ctx.mkFuncDecl(fname, domain, bs); Expr fapp = ctx.mkApp(f, ctx.mkConst(x, bs), ctx.mkConst(y, bs)); Expr[] fargs2 = { ctx.mkFreshConst("cp", bs) }; Sort[] domain2 = { bs }; Expr fapp2 = ctx.mkApp(ctx.mkFreshFuncDecl("fp", domain2, bs), fargs2); BoolExpr trivial_eq = ctx.mkEq(fapp, fapp); BoolExpr nontrivial_eq = ctx.mkEq(fapp, fapp2); Goal g = ctx.mkGoal(true, false, false); g.add(trivial_eq); g.add(nontrivial_eq); System.out.println("Goal: " + g); Solver solver = ctx.mkSolver(); for (BoolExpr a : g.getFormulas()) solver.add(a); if (solver.check() != Status.SATISFIABLE) throw new TestFailedException(); ApplyResult ar = applyTactic(ctx, ctx.mkTactic("simplify"), g); if (ar.getNumSubgoals() == 1 && (ar.getSubgoals()[0].isDecidedSat() || ar.getSubgoals()[0] .isDecidedUnsat())) throw new TestFailedException(); ar = applyTactic(ctx, ctx.mkTactic("smt"), g); if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedSat()) throw new TestFailedException(); g.add(ctx.mkEq(ctx.mkNumeral(1, ctx.mkBitVecSort(32)), ctx.mkNumeral(2, ctx.mkBitVecSort(32)))); ar = applyTactic(ctx, ctx.mkTactic("smt"), g); if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedUnsat()) throw new TestFailedException(); Goal g2 = ctx.mkGoal(true, true, false); ar = applyTactic(ctx, ctx.mkTactic("smt"), g2); if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedSat()) throw new TestFailedException(); g2 = ctx.mkGoal(true, true, false); g2.add(ctx.mkFalse()); ar = applyTactic(ctx, ctx.mkTactic("smt"), g2); if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedUnsat()) throw new TestFailedException(); Goal g3 = ctx.mkGoal(true, true, false); Expr xc = ctx.mkConst(ctx.mkSymbol("x"), ctx.getIntSort()); Expr yc = ctx.mkConst(ctx.mkSymbol("y"), ctx.getIntSort()); g3.add(ctx.mkEq(xc, ctx.mkNumeral(1, ctx.getIntSort()))); g3.add(ctx.mkEq(yc, ctx.mkNumeral(2, ctx.getIntSort()))); BoolExpr constr = ctx.mkEq(xc, yc); g3.add(constr); ar = applyTactic(ctx, ctx.mkTactic("smt"), g3); if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedUnsat()) throw new TestFailedException(); modelConverterTest(ctx); // Real num/den test. RatNum rn = ctx.mkReal(42, 43); Expr inum = rn.getNumerator(); Expr iden = rn.getDenominator(); System.out.println("Numerator: " + inum + " Denominator: " + iden); if (!inum.toString().equals("42") || !iden.toString().equals("43")) throw new TestFailedException(); if (!rn.toDecimalString(3).toString().equals("0.976?")) throw new TestFailedException(); bigIntCheck(ctx, ctx.mkReal("-1231231232/234234333")); bigIntCheck(ctx, ctx.mkReal("-123123234234234234231232/234234333")); bigIntCheck(ctx, ctx.mkReal("-234234333")); bigIntCheck(ctx, ctx.mkReal("234234333/2")); String bn = "1234567890987654321"; if (!ctx.mkInt(bn).getBigInteger().toString().equals(bn)) throw new TestFailedException(); if (!ctx.mkBV(bn, 128).getBigInteger().toString().equals(bn)) throw new TestFailedException(); if (ctx.mkBV(bn, 32).getBigInteger().toString().equals(bn)) throw new TestFailedException(); // Error handling test. try { @SuppressWarnings("unused") IntExpr i = ctx.mkInt("1/2"); throw new TestFailedException(); // unreachable } catch (Z3Exception e) { } } // / Some basic expression casting tests. void castingTest(Context ctx) throws TestFailedException { System.out.println("CastingTest"); Sort[] domain = { ctx.getBoolSort(), ctx.getBoolSort() }; FuncDecl f = ctx.mkFuncDecl("f", domain, ctx.getBoolSort()); AST upcast = ctx.mkFuncDecl(ctx.mkSymbol("q"), domain, ctx.getBoolSort()); try { @SuppressWarnings("unused") FuncDecl downcast = (FuncDecl) f; // OK } catch (ClassCastException e) { throw new TestFailedException(); } try { @SuppressWarnings("unused") Expr uc = (Expr) upcast; throw new TestFailedException(); // should not be reachable! } catch (ClassCastException e) { } Symbol s = ctx.mkSymbol(42); IntSymbol si = (s.getClass() == IntSymbol.class) ? (IntSymbol) s : null; if (si == null) throw new TestFailedException(); try { @SuppressWarnings("unused") IntSymbol si2 = (IntSymbol) s; } catch (ClassCastException e) { throw new TestFailedException(); } s = ctx.mkSymbol("abc"); StringSymbol ss = (s.getClass() == StringSymbol.class) ? (StringSymbol) s : null; if (ss == null) throw new TestFailedException(); try { @SuppressWarnings("unused") StringSymbol ss2 = (StringSymbol) s; } catch (ClassCastException e) { throw new TestFailedException(); } try { @SuppressWarnings("unused") IntSymbol si2 = (IntSymbol) s; throw new TestFailedException(); // unreachable } catch (Exception e) { } Sort srt = ctx.mkBitVecSort(32); BitVecSort bvs = null; try { bvs = (BitVecSort) srt; } catch (ClassCastException e) { throw new TestFailedException(); } if (bvs.getSize() != 32) throw new TestFailedException(); Expr q = ctx.mkAdd(ctx.mkInt(1), ctx.mkInt(2)); Expr q2 = q.getArgs()[1]; Sort qs = q2.getSort(); if (qs.getClass() != IntSort.class) throw new TestFailedException(); try { @SuppressWarnings("unused") IntSort isrt = (IntSort) qs; } catch (ClassCastException e) { throw new TestFailedException(); } AST a = ctx.mkInt(42); try { Expr.class.cast(a); } catch (ClassCastException e) { throw new TestFailedException(); } try { ArithExpr.class.cast(a); } catch (ClassCastException e) { throw new TestFailedException(); } try { IntExpr.class.cast(a); } catch (ClassCastException e) { throw new TestFailedException(); } try { IntNum.class.cast(a); } catch (ClassCastException e) { throw new TestFailedException(); } Expr[][] earr = new Expr[2][]; earr[0] = new Expr[2]; earr[1] = new Expr[2]; earr[0][0] = ctx.mkTrue(); earr[0][1] = ctx.mkTrue(); earr[1][0] = ctx.mkFalse(); earr[1][1] = ctx.mkFalse(); for (Expr[] ea : earr) for (Expr e : ea) { try { Expr ns = ctx.mkNot((BoolExpr) e); @SuppressWarnings("unused") BoolExpr ens = (BoolExpr) ns; } catch (ClassCastException ex) { throw new TestFailedException(); } } } // / Shows how to read an SMT2 file. void smt2FileTest(String filename) { Date before = new Date(); System.out.println("SMT2 File test "); System.gc(); { HashMap<String, String> cfg = new HashMap<String, String>(); cfg.put("model", "true"); Context ctx = new Context(cfg); BoolExpr a = ctx.mkAnd(ctx.parseSMTLIB2File(filename, null, null, null, null)); long t_diff = ((new Date()).getTime() - before.getTime()) / 1000; System.out.println("SMT2 file read time: " + t_diff + " sec"); // Iterate over the formula. LinkedList<Expr> q = new LinkedList<Expr>(); q.add(a); int cnt = 0; while (q.size() > 0) { AST cur = (AST) q.removeFirst(); cnt++; if (cur.getClass() == Expr.class) if (!(cur.isVar())) for (Expr c : ((Expr) cur).getArgs()) q.add(c); } System.out.println(cnt + " ASTs"); } long t_diff = ((new Date()).getTime() - before.getTime()) / 1000; System.out.println("SMT2 file test took " + t_diff + " sec"); } // / Shows how to use Solver(logic) // / @param ctx void logicExample(Context ctx) throws TestFailedException { System.out.println("LogicTest"); Log.append("LogicTest"); com.microsoft.z3.Global.ToggleWarningMessages(true); BitVecSort bvs = ctx.mkBitVecSort(32); Expr x = ctx.mkConst("x", bvs); Expr y = ctx.mkConst("y", bvs); BoolExpr eq = ctx.mkEq(x, y); // Use a solver for QF_BV Solver s = ctx.mkSolver("QF_BV"); s.add(eq); Status res = s.check(); System.out.println("solver result: " + res); // Or perhaps a tactic for QF_BV Goal g = ctx.mkGoal(true, false, false); g.add(eq); Tactic t = ctx.mkTactic("qfbv"); ApplyResult ar = t.apply(g); System.out.println("tactic result: " + ar); if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedSat()) throw new TestFailedException(); } // / Demonstrates how to use the ParOr tactic. void parOrExample(Context ctx) throws TestFailedException { System.out.println("ParOrExample"); Log.append("ParOrExample"); BitVecSort bvs = ctx.mkBitVecSort(32); Expr x = ctx.mkConst("x", bvs); Expr y = ctx.mkConst("y", bvs); BoolExpr q = ctx.mkEq(x, y); Goal g = ctx.mkGoal(true, false, false); g.add(q); Tactic t1 = ctx.mkTactic("qfbv"); Tactic t2 = ctx.mkTactic("qfbv"); Tactic p = ctx.parOr(t1, t2); ApplyResult ar = p.apply(g); if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedSat()) throw new TestFailedException(); } void bigIntCheck(Context ctx, RatNum r) { System.out.println("Num: " + r.getBigIntNumerator()); System.out.println("Den: " + r.getBigIntDenominator()); } // / Find a model for <code>x xor y</code>. public void findModelExample1(Context ctx) throws TestFailedException { System.out.println("FindModelExample1"); Log.append("FindModelExample1"); BoolExpr x = ctx.mkBoolConst("x"); BoolExpr y = ctx.mkBoolConst("y"); BoolExpr x_xor_y = ctx.mkXor(x, y); Model model = check(ctx, x_xor_y, Status.SATISFIABLE); System.out.println("x = " + model.evaluate(x, false) + ", y = " + model.evaluate(y, false)); } // / Find a model for <tt>x < y + 1, x > 2</tt>. // / Then, assert <tt>not(x = y)</tt>, and find another model. public void findModelExample2(Context ctx) throws TestFailedException { System.out.println("FindModelExample2"); Log.append("FindModelExample2"); IntExpr x = ctx.mkIntConst("x"); IntExpr y = ctx.mkIntConst("y"); IntExpr one = ctx.mkInt(1); IntExpr two = ctx.mkInt(2); ArithExpr y_plus_one = ctx.mkAdd(y, one); BoolExpr c1 = ctx.mkLt(x, y_plus_one); BoolExpr c2 = ctx.mkGt(x, two); BoolExpr q = ctx.mkAnd(c1, c2); System.out.println("model for: x < y + 1, x > 2"); Model model = check(ctx, q, Status.SATISFIABLE); System.out.println("x = " + model.evaluate(x, false) + ", y =" + model.evaluate(y, false)); /* assert not(x = y) */ BoolExpr x_eq_y = ctx.mkEq(x, y); BoolExpr c3 = ctx.mkNot(x_eq_y); q = ctx.mkAnd(q, c3); System.out.println("model for: x < y + 1, x > 2, not(x = y)"); model = check(ctx, q, Status.SATISFIABLE); System.out.println("x = " + model.evaluate(x, false) + ", y = " + model.evaluate(y, false)); } // / Prove <tt>x = y implies g(x) = g(y)</tt>, and // / disprove <tt>x = y implies g(g(x)) = g(y)</tt>. // / <remarks>This function demonstrates how to create uninterpreted // / types and functions.</remarks> public void proveExample1(Context ctx) throws TestFailedException { System.out.println("ProveExample1"); Log.append("ProveExample1"); /* create uninterpreted type. */ Sort U = ctx.mkUninterpretedSort(ctx.mkSymbol("U")); /* declare function g */ FuncDecl g = ctx.mkFuncDecl("g", U, U); /* create x and y */ Expr x = ctx.mkConst("x", U); Expr y = ctx.mkConst("y", U); /* create g(x), g(y) */ Expr gx = g.apply(x); Expr gy = g.apply(y); /* assert x = y */ BoolExpr eq = ctx.mkEq(x, y); /* prove g(x) = g(y) */ BoolExpr f = ctx.mkEq(gx, gy); System.out.println("prove: x = y implies g(x) = g(y)"); prove(ctx, ctx.mkImplies(eq, f), false); /* create g(g(x)) */ Expr ggx = g.apply(gx); /* disprove g(g(x)) = g(y) */ f = ctx.mkEq(ggx, gy); System.out.println("disprove: x = y implies g(g(x)) = g(y)"); disprove(ctx, ctx.mkImplies(eq, f), false); /* Print the model using the custom model printer */ Model m = check(ctx, ctx.mkNot(f), Status.SATISFIABLE); System.out.println(m); } // / Prove <tt>not(g(g(x) - g(y)) = g(z)), x + z <= y <= x implies z < 0 // </tt>. // / Then, show that <tt>z < -1</tt> is not implied. // / <remarks>This example demonstrates how to combine uninterpreted // functions // / and arithmetic.</remarks> public void proveExample2(Context ctx) throws TestFailedException { System.out.println("ProveExample2"); Log.append("ProveExample2"); /* declare function g */ Sort I = ctx.getIntSort(); FuncDecl g = ctx.mkFuncDecl("g", I, I); /* create x, y, and z */ IntExpr x = ctx.mkIntConst("x"); IntExpr y = ctx.mkIntConst("y"); IntExpr z = ctx.mkIntConst("z"); /* create gx, gy, gz */ Expr gx = ctx.mkApp(g, x); Expr gy = ctx.mkApp(g, y); Expr gz = ctx.mkApp(g, z); /* create zero */ IntExpr zero = ctx.mkInt(0); /* assert not(g(g(x) - g(y)) = g(z)) */ ArithExpr gx_gy = ctx.mkSub((IntExpr) gx, (IntExpr) gy); Expr ggx_gy = ctx.mkApp(g, gx_gy); BoolExpr eq = ctx.mkEq(ggx_gy, gz); BoolExpr c1 = ctx.mkNot(eq); /* assert x + z <= y */ ArithExpr x_plus_z = ctx.mkAdd(x, z); BoolExpr c2 = ctx.mkLe(x_plus_z, y); /* assert y <= x */ BoolExpr c3 = ctx.mkLe(y, x); /* prove z < 0 */ BoolExpr f = ctx.mkLt(z, zero); System.out .println("prove: not(g(g(x) - g(y)) = g(z)), x + z <= y <= x implies z < 0"); prove(ctx, f, false, c1, c2, c3); /* disprove z < -1 */ IntExpr minus_one = ctx.mkInt(-1); f = ctx.mkLt(z, minus_one); System.out .println("disprove: not(g(g(x) - g(y)) = g(z)), x + z <= y <= x implies z < -1"); disprove(ctx, f, false, c1, c2, c3); } // / Show how push & pop can be used to create "backtracking" points. // / <remarks>This example also demonstrates how big numbers can be // / created in ctx.</remarks> public void pushPopExample1(Context ctx) throws TestFailedException { System.out.println("PushPopExample1"); Log.append("PushPopExample1"); /* create a big number */ IntSort int_type = ctx.getIntSort(); IntExpr big_number = ctx .mkInt("1000000000000000000000000000000000000000000000000000000"); /* create number 3 */ IntExpr three = (IntExpr) ctx.mkNumeral("3", int_type); /* create x */ IntExpr x = ctx.mkIntConst("x"); Solver solver = ctx.mkSolver(); /* assert x >= "big number" */ BoolExpr c1 = ctx.mkGe(x, big_number); System.out.println("assert: x >= 'big number'"); solver.add(c1); /* create a backtracking point */ System.out.println("push"); solver.push(); /* assert x <= 3 */ BoolExpr c2 = ctx.mkLe(x, three); System.out.println("assert: x <= 3"); solver.add(c2); /* context is inconsistent at this point */ if (solver.check() != Status.UNSATISFIABLE) throw new TestFailedException(); /* * backtrack: the constraint x <= 3 will be removed, since it was * asserted after the last ctx.Push. */ System.out.println("pop"); solver.pop(1); /* the context is consistent again. */ if (solver.check() != Status.SATISFIABLE) throw new TestFailedException(); /* new constraints can be asserted... */ /* create y */ IntExpr y = ctx.mkIntConst("y"); /* assert y > x */ BoolExpr c3 = ctx.mkGt(y, x); System.out.println("assert: y > x"); solver.add(c3); /* the context is still consistent. */ if (solver.check() != Status.SATISFIABLE) throw new TestFailedException(); } // / Tuples. // / <remarks>Check that the projection of a tuple // / returns the corresponding element.</remarks> public void tupleExample(Context ctx) throws TestFailedException { System.out.println("TupleExample"); Log.append("TupleExample"); Sort int_type = ctx.getIntSort(); TupleSort tuple = ctx.mkTupleSort(ctx.mkSymbol("mk_tuple"), // name of // tuple // constructor new Symbol[] { ctx.mkSymbol("first"), ctx.mkSymbol("second") }, // names // of // projection // operators new Sort[] { int_type, int_type } // types of projection // operators ); FuncDecl first = tuple.getFieldDecls()[0]; // declarations are for // projections @SuppressWarnings("unused") FuncDecl second = tuple.getFieldDecls()[1]; Expr x = ctx.mkConst("x", int_type); Expr y = ctx.mkConst("y", int_type); Expr n1 = tuple.mkDecl().apply(x, y); Expr n2 = first.apply(n1); BoolExpr n3 = ctx.mkEq(x, n2); System.out.println("Tuple example: " + n3); prove(ctx, n3, false); } // / Simple bit-vector example. // / <remarks> // / This example disproves that x - 10 &lt;= 0 IFF x &lt;= 10 for (32-bit) // machine integers // / </remarks> public void bitvectorExample1(Context ctx) throws TestFailedException { System.out.println("BitvectorExample1"); Log.append("BitvectorExample1"); BitVecSort bv_type = ctx.mkBitVecSort(32); BitVecExpr x = (BitVecExpr) ctx.mkConst("x", bv_type); BitVecNum zero = (BitVecNum) ctx.mkNumeral("0", bv_type); BitVecNum ten = ctx.mkBV(10, 32); BitVecExpr x_minus_ten = ctx.mkBVSub(x, ten); /* bvsle is signed less than or equal to */ BoolExpr c1 = ctx.mkBVSLE(x, ten); BoolExpr c2 = ctx.mkBVSLE(x_minus_ten, zero); BoolExpr thm = ctx.mkIff(c1, c2); System.out .println("disprove: x - 10 <= 0 IFF x <= 10 for (32-bit) machine integers"); disprove(ctx, thm, false); } // / Find x and y such that: x ^ y - 103 == x * y public void bitvectorExample2(Context ctx) throws TestFailedException { System.out.println("BitvectorExample2"); Log.append("BitvectorExample2"); /* construct x ^ y - 103 == x * y */ BitVecSort bv_type = ctx.mkBitVecSort(32); BitVecExpr x = ctx.mkBVConst("x", 32); BitVecExpr y = ctx.mkBVConst("y", 32); BitVecExpr x_xor_y = ctx.mkBVXOR(x, y); BitVecExpr c103 = (BitVecNum) ctx.mkNumeral("103", bv_type); BitVecExpr lhs = ctx.mkBVSub(x_xor_y, c103); BitVecExpr rhs = ctx.mkBVMul(x, y); BoolExpr ctr = ctx.mkEq(lhs, rhs); System.out .println("find values of x and y, such that x ^ y - 103 == x * y"); /* find a model (i.e., values for x an y that satisfy the constraint */ Model m = check(ctx, ctr, Status.SATISFIABLE); System.out.println(m); } // / Demonstrates how to use the SMTLIB parser. public void parserExample1(Context ctx) throws TestFailedException { System.out.println("ParserExample1"); Log.append("ParserExample1"); BoolExpr f = ctx.parseSMTLIB2String( "(declare-const x Int) (declare-const y Int) (assert (and (> x y) (> x 0)))", null, null, null, null)[0]; System.out.println("formula " + f); @SuppressWarnings("unused") Model m = check(ctx, f, Status.SATISFIABLE); } // / Demonstrates how to initialize the parser symbol table. public void parserExample2(Context ctx) throws TestFailedException { System.out.println("ParserExample2"); Log.append("ParserExample2"); Symbol[] declNames = { ctx.mkSymbol("a"), ctx.mkSymbol("b") }; FuncDecl a = ctx.mkConstDecl(declNames[0], ctx.mkIntSort()); FuncDecl b = ctx.mkConstDecl(declNames[1], ctx.mkIntSort()); FuncDecl[] decls = new FuncDecl[] { a, b }; BoolExpr f = ctx.parseSMTLIB2String("(assert (> a b))", null, null, declNames, decls)[0]; System.out.println("formula: " + f); check(ctx, f, Status.SATISFIABLE); } // / Demonstrates how to initialize the parser symbol table. public void parserExample3(Context ctx) throws Exception { System.out.println("ParserExample3"); Log.append("ParserExample3"); /* declare function g */ Sort I = ctx.mkIntSort(); FuncDecl g = ctx.mkFuncDecl("g", new Sort[] { I, I }, I); BoolExpr ca = commAxiom(ctx, g); BoolExpr thm = ctx.parseSMTLIB2String( "(declare-fun (Int Int) Int) (assert (forall ((x Int) (y Int)) (=> (= x y) (= (gg x 0) (gg 0 y)))))", null, null, new Symbol[] { ctx.mkSymbol("gg") }, new FuncDecl[] { g })[0]; System.out.println("formula: " + thm); prove(ctx, thm, false, ca); } // / Demonstrates how to handle parser errors using Z3 error handling // support. // / <remarks></remarks> public void parserExample5(Context ctx) { System.out.println("ParserExample5"); try { ctx.parseSMTLIB2String( /* * the following string has a parsing error: missing * parenthesis */ "(declare-const x Int (declare-const y Int)) (assert (> x y))", null, null, null, null); } catch (Z3Exception e) { System.out.println("Z3 error: " + e); } } // / Create an ite-Expr (if-then-else Exprs). public void iteExample(Context ctx) { System.out.println("ITEExample"); Log.append("ITEExample"); BoolExpr f = ctx.mkFalse(); Expr one = ctx.mkInt(1); Expr zero = ctx.mkInt(0); Expr ite = ctx.mkITE(f, one, zero); System.out.println("Expr: " + ite); } // / Create an enumeration data type. public void enumExample(Context ctx) throws TestFailedException { System.out.println("EnumExample"); Log.append("EnumExample"); Symbol name = ctx.mkSymbol("fruit"); EnumSort fruit = ctx.mkEnumSort(name, ctx.mkSymbol("apple"), ctx.mkSymbol("banana"), ctx.mkSymbol("orange")); System.out.println((fruit.getConsts()[0])); System.out.println((fruit.getConsts()[1])); System.out.println((fruit.getConsts()[2])); System.out.println((fruit.getTesterDecls()[0])); System.out.println((fruit.getTesterDecls()[1])); System.out.println((fruit.getTesterDecls()[2])); Expr apple = fruit.getConsts()[0]; Expr banana = fruit.getConsts()[1]; Expr orange = fruit.getConsts()[2]; /* Apples are different from oranges */ prove(ctx, ctx.mkNot(ctx.mkEq(apple, orange)), false); /* Apples pass the apple test */ prove(ctx, (BoolExpr) ctx.mkApp(fruit.getTesterDecls()[0], apple), false); /* Oranges fail the apple test */ disprove(ctx, (BoolExpr) ctx.mkApp(fruit.getTesterDecls()[0], orange), false); prove(ctx, (BoolExpr) ctx.mkNot((BoolExpr) ctx.mkApp( fruit.getTesterDecls()[0], orange)), false); Expr fruity = ctx.mkConst("fruity", fruit); /* If something is fruity, then it is an apple, banana, or orange */ prove(ctx, ctx.mkOr(ctx.mkEq(fruity, apple), ctx.mkEq(fruity, banana), ctx.mkEq(fruity, orange)), false); } // / Create a list datatype. public void listExample(Context ctx) throws TestFailedException { System.out.println("ListExample"); Log.append("ListExample"); Sort int_ty; ListSort int_list; Expr nil, l1, l2, x, y, u, v; BoolExpr fml, fml1; int_ty = ctx.mkIntSort(); int_list = ctx.mkListSort(ctx.mkSymbol("int_list"), int_ty); nil = ctx.mkConst(int_list.getNilDecl()); l1 = ctx.mkApp(int_list.getConsDecl(), ctx.mkInt(1), nil); l2 = ctx.mkApp(int_list.getConsDecl(), ctx.mkInt(2), nil); /* nil != cons(1, nil) */ prove(ctx, ctx.mkNot(ctx.mkEq(nil, l1)), false); /* cons(2,nil) != cons(1, nil) */ prove(ctx, ctx.mkNot(ctx.mkEq(l1, l2)), false); /* cons(x,nil) = cons(y, nil) => x = y */ x = ctx.mkConst("x", int_ty); y = ctx.mkConst("y", int_ty); l1 = ctx.mkApp(int_list.getConsDecl(), x, nil); l2 = ctx.mkApp(int_list.getConsDecl(), y, nil); prove(ctx, ctx.mkImplies(ctx.mkEq(l1, l2), ctx.mkEq(x, y)), false); /* cons(x,u) = cons(x, v) => u = v */ u = ctx.mkConst("u", int_list); v = ctx.mkConst("v", int_list); l1 = ctx.mkApp(int_list.getConsDecl(), x, u); l2 = ctx.mkApp(int_list.getConsDecl(), y, v); prove(ctx, ctx.mkImplies(ctx.mkEq(l1, l2), ctx.mkEq(u, v)), false); prove(ctx, ctx.mkImplies(ctx.mkEq(l1, l2), ctx.mkEq(x, y)), false); /* is_nil(u) or is_cons(u) */ prove(ctx, ctx.mkOr((BoolExpr) ctx.mkApp(int_list.getIsNilDecl(), u), (BoolExpr) ctx.mkApp(int_list.getIsConsDecl(), u)), false); /* occurs check u != cons(x,u) */ prove(ctx, ctx.mkNot(ctx.mkEq(u, l1)), false); /* destructors: is_cons(u) => u = cons(head(u),tail(u)) */ fml1 = ctx.mkEq( u, ctx.mkApp(int_list.getConsDecl(), ctx.mkApp(int_list.getHeadDecl(), u), ctx.mkApp(int_list.getTailDecl(), u))); fml = ctx.mkImplies((BoolExpr) ctx.mkApp(int_list.getIsConsDecl(), u), fml1); System.out.println("Formula " + fml); prove(ctx, fml, false); disprove(ctx, fml1, false); } // / Create a binary tree datatype. public void treeExample(Context ctx) throws TestFailedException { System.out.println("TreeExample"); Log.append("TreeExample"); Sort cell; FuncDecl nil_decl, is_nil_decl, cons_decl, is_cons_decl, car_decl, cdr_decl; Expr nil, l1, l2, x, y, u, v; BoolExpr fml, fml1; String[] head_tail = new String[] { "car", "cdr" }; Sort[] sorts = new Sort[] { null, null }; int[] sort_refs = new int[] { 0, 0 }; Constructor nil_con, cons_con; nil_con = ctx.mkConstructor("nil", "is_nil", null, null, null); cons_con = ctx.mkConstructor("cons", "is_cons", head_tail, sorts, sort_refs); Constructor[] constructors = new Constructor[] { nil_con, cons_con }; cell = ctx.mkDatatypeSort("cell", constructors); nil_decl = nil_con.ConstructorDecl(); is_nil_decl = nil_con.getTesterDecl(); cons_decl = cons_con.ConstructorDecl(); is_cons_decl = cons_con.getTesterDecl(); FuncDecl[] cons_accessors = cons_con.getAccessorDecls(); car_decl = cons_accessors[0]; cdr_decl = cons_accessors[1]; nil = ctx.mkConst(nil_decl); l1 = ctx.mkApp(cons_decl, nil, nil); l2 = ctx.mkApp(cons_decl, l1, nil); /* nil != cons(nil, nil) */ prove(ctx, ctx.mkNot(ctx.mkEq(nil, l1)), false); /* cons(x,u) = cons(x, v) => u = v */ u = ctx.mkConst("u", cell); v = ctx.mkConst("v", cell); x = ctx.mkConst("x", cell); y = ctx.mkConst("y", cell); l1 = ctx.mkApp(cons_decl, x, u); l2 = ctx.mkApp(cons_decl, y, v); prove(ctx, ctx.mkImplies(ctx.mkEq(l1, l2), ctx.mkEq(u, v)), false); prove(ctx, ctx.mkImplies(ctx.mkEq(l1, l2), ctx.mkEq(x, y)), false); /* is_nil(u) or is_cons(u) */ prove(ctx, ctx.mkOr((BoolExpr) ctx.mkApp(is_nil_decl, u), (BoolExpr) ctx.mkApp(is_cons_decl, u)), false); /* occurs check u != cons(x,u) */ prove(ctx, ctx.mkNot(ctx.mkEq(u, l1)), false); /* destructors: is_cons(u) => u = cons(car(u),cdr(u)) */ fml1 = ctx.mkEq( u, ctx.mkApp(cons_decl, ctx.mkApp(car_decl, u), ctx.mkApp(cdr_decl, u))); fml = ctx.mkImplies((BoolExpr) ctx.mkApp(is_cons_decl, u), fml1); System.out.println("Formula " + fml); prove(ctx, fml, false); disprove(ctx, fml1, false); } // / Create a forest of trees. // / <remarks> // / forest ::= nil | cons(tree, forest) // / tree ::= nil | cons(forest, forest) // / </remarks> public void forestExample(Context ctx) throws TestFailedException { System.out.println("ForestExample"); Log.append("ForestExample"); Sort tree, forest; @SuppressWarnings("unused") FuncDecl nil1_decl, is_nil1_decl, cons1_decl, is_cons1_decl, car1_decl, cdr1_decl; @SuppressWarnings("unused") FuncDecl nil2_decl, is_nil2_decl, cons2_decl, is_cons2_decl, car2_decl, cdr2_decl; @SuppressWarnings("unused") Expr nil1, nil2, t1, t2, t3, t4, f1, f2, f3, l1, l2, x, y, u, v; // // Declare the names of the accessors for cons. // Then declare the sorts of the accessors. // For this example, all sorts refer to the new types 'forest' and // 'tree' // being declared, so we pass in null for both sorts1 and sorts2. // On the other hand, the sort_refs arrays contain the indices of the // two new sorts being declared. The first element in sort1_refs // points to 'tree', which has index 1, the second element in sort1_refs // array // points to 'forest', which has index 0. // Symbol[] head_tail1 = new Symbol[] { ctx.mkSymbol("head"), ctx.mkSymbol("tail") }; Sort[] sorts1 = new Sort[] { null, null }; int[] sort1_refs = new int[] { 1, 0 }; // the first item points to a // tree, the second to a forest Symbol[] head_tail2 = new Symbol[] { ctx.mkSymbol("car"), ctx.mkSymbol("cdr") }; Sort[] sorts2 = new Sort[] { null, null }; int[] sort2_refs = new int[] { 0, 0 }; // both items point to the forest // datatype. Constructor nil1_con, cons1_con, nil2_con, cons2_con; Constructor[] constructors1 = new Constructor[2], constructors2 = new Constructor[2]; Symbol[] sort_names = { ctx.mkSymbol("forest"), ctx.mkSymbol("tree") }; /* build a forest */ nil1_con = ctx.mkConstructor(ctx.mkSymbol("nil"), ctx.mkSymbol("is_nil"), null, null, null); cons1_con = ctx.mkConstructor(ctx.mkSymbol("cons1"), ctx.mkSymbol("is_cons1"), head_tail1, sorts1, sort1_refs); constructors1[0] = nil1_con; constructors1[1] = cons1_con; /* build a tree */ nil2_con = ctx.mkConstructor(ctx.mkSymbol("nil2"), ctx.mkSymbol("is_nil2"), null, null, null); cons2_con = ctx.mkConstructor(ctx.mkSymbol("cons2"), ctx.mkSymbol("is_cons2"), head_tail2, sorts2, sort2_refs); constructors2[0] = nil2_con; constructors2[1] = cons2_con; Constructor[][] clists = new Constructor[][] { constructors1, constructors2 }; Sort[] sorts = ctx.mkDatatypeSorts(sort_names, clists); forest = sorts[0]; tree = sorts[1]; // // Now that the datatype has been created. // Query the constructors for the constructor // functions, testers, and field accessors. // nil1_decl = nil1_con.ConstructorDecl(); is_nil1_decl = nil1_con.getTesterDecl(); cons1_decl = cons1_con.ConstructorDecl(); is_cons1_decl = cons1_con.getTesterDecl(); FuncDecl[] cons1_accessors = cons1_con.getAccessorDecls(); car1_decl = cons1_accessors[0]; cdr1_decl = cons1_accessors[1]; nil2_decl = nil2_con.ConstructorDecl(); is_nil2_decl = nil2_con.getTesterDecl(); cons2_decl = cons2_con.ConstructorDecl(); is_cons2_decl = cons2_con.getTesterDecl(); FuncDecl[] cons2_accessors = cons2_con.getAccessorDecls(); car2_decl = cons2_accessors[0]; cdr2_decl = cons2_accessors[1]; nil1 = ctx.mkConst(nil1_decl); nil2 = ctx.mkConst(nil2_decl); f1 = ctx.mkApp(cons1_decl, nil2, nil1); t1 = ctx.mkApp(cons2_decl, nil1, nil1); t2 = ctx.mkApp(cons2_decl, f1, nil1); t3 = ctx.mkApp(cons2_decl, f1, f1); t4 = ctx.mkApp(cons2_decl, nil1, f1); f2 = ctx.mkApp(cons1_decl, t1, nil1); f3 = ctx.mkApp(cons1_decl, t1, f1); /* nil != cons(nil,nil) */ prove(ctx, ctx.mkNot(ctx.mkEq(nil1, f1)), false); prove(ctx, ctx.mkNot(ctx.mkEq(nil2, t1)), false); /* cons(x,u) = cons(x, v) => u = v */ u = ctx.mkConst("u", forest); v = ctx.mkConst("v", forest); x = ctx.mkConst("x", tree); y = ctx.mkConst("y", tree); l1 = ctx.mkApp(cons1_decl, x, u); l2 = ctx.mkApp(cons1_decl, y, v); prove(ctx, ctx.mkImplies(ctx.mkEq(l1, l2), ctx.mkEq(u, v)), false); prove(ctx, ctx.mkImplies(ctx.mkEq(l1, l2), ctx.mkEq(x, y)), false); /* is_nil(u) or is_cons(u) */ prove(ctx, ctx.mkOr((BoolExpr) ctx.mkApp(is_nil1_decl, u), (BoolExpr) ctx.mkApp(is_cons1_decl, u)), false); /* occurs check u != cons(x,u) */ prove(ctx, ctx.mkNot(ctx.mkEq(u, l1)), false); } // / Demonstrate how to use #Eval. public void evalExample1(Context ctx) { System.out.println("EvalExample1"); Log.append("EvalExample1"); IntExpr x = ctx.mkIntConst("x"); IntExpr y = ctx.mkIntConst("y"); IntExpr two = ctx.mkInt(2); Solver solver = ctx.mkSolver(); /* assert x < y */ solver.add(ctx.mkLt(x, y)); /* assert x > 2 */ solver.add(ctx.mkGt(x, two)); /* find model for the constraints above */ Model model = null; if (Status.SATISFIABLE == solver.check()) { model = solver.getModel(); System.out.println(model); System.out.println("\nevaluating x+y"); Expr v = model.evaluate(ctx.mkAdd(x, y), false); if (v != null) { System.out.println("result = " + (v)); } else { System.out.println("Failed to evaluate: x+y"); } } else { System.out.println("BUG, the constraints are not satisfiable."); } } // / Demonstrate how to use #Eval on tuples. public void evalExample2(Context ctx) { System.out.println("EvalExample2"); Log.append("EvalExample2"); Sort int_type = ctx.getIntSort(); TupleSort tuple = ctx.mkTupleSort(ctx.mkSymbol("mk_tuple"), // name of // tuple // constructor new Symbol[] { ctx.mkSymbol("first"), ctx.mkSymbol("second") }, // names // of // projection // operators new Sort[] { int_type, int_type } // types of projection // operators ); FuncDecl first = tuple.getFieldDecls()[0]; // declarations are for // projections FuncDecl second = tuple.getFieldDecls()[1]; Expr tup1 = ctx.mkConst("t1", tuple); Expr tup2 = ctx.mkConst("t2", tuple); Solver solver = ctx.mkSolver(); /* assert tup1 != tup2 */ solver.add(ctx.mkNot(ctx.mkEq(tup1, tup2))); /* assert first tup1 = first tup2 */ solver.add(ctx.mkEq(ctx.mkApp(first, tup1), ctx.mkApp(first, tup2))); /* find model for the constraints above */ Model model = null; if (Status.SATISFIABLE == solver.check()) { model = solver.getModel(); System.out.println(model); System.out.println("evaluating tup1 " + (model.evaluate(tup1, false))); System.out.println("evaluating tup2 " + (model.evaluate(tup2, false))); System.out.println("evaluating second(tup2) " + (model.evaluate(ctx.mkApp(second, tup2), false))); } else { System.out.println("BUG, the constraints are satisfiable."); } } // / Demonstrate how to use <code>Push</code>and <code>Pop</code>to // / control the size of models. // / <remarks>Note: this test is specialized to 32-bit bitvectors.</remarks> public void checkSmall(Context ctx, Solver solver, BitVecExpr... to_minimize) { int num_Exprs = to_minimize.length; int[] upper = new int[num_Exprs]; int[] lower = new int[num_Exprs]; for (int i = 0; i < upper.length; ++i) { upper[i] = Integer.MAX_VALUE; lower[i] = 0; } boolean some_work = true; int last_index = -1; int last_upper = 0; while (some_work) { solver.push(); boolean check_is_sat = true; while (check_is_sat && some_work) { // Assert all feasible bounds. for (int i = 0; i < num_Exprs; ++i) { solver.add(ctx.mkBVULE(to_minimize[i], ctx.mkBV(upper[i], 32))); } check_is_sat = Status.SATISFIABLE == solver.check(); if (!check_is_sat) { if (last_index != -1) { lower[last_index] = last_upper + 1; } break; } System.out.println(solver.getModel()); // narrow the bounds based on the current model. for (int i = 0; i < num_Exprs; ++i) { Expr v = solver.getModel().evaluate(to_minimize[i], false); int ui = ((BitVecNum) v).getInt(); if (ui < upper[i]) { upper[i] = (int) ui; } System.out.println(i + " " + lower[i] + " " + upper[i]); } // find a new bound to add some_work = false; last_index = 0; for (int i = 0; i < num_Exprs; ++i) { if (lower[i] < upper[i]) { last_upper = (upper[i] + lower[i]) / 2; last_index = i; solver.add(ctx.mkBVULE(to_minimize[i], ctx.mkBV(last_upper, 32))); some_work = true; break; } } } solver.pop(); } } // / Reduced-size model generation example. public void findSmallModelExample(Context ctx) { System.out.println("FindSmallModelExample"); Log.append("FindSmallModelExample"); BitVecExpr x = ctx.mkBVConst("x", 32); BitVecExpr y = ctx.mkBVConst("y", 32); BitVecExpr z = ctx.mkBVConst("z", 32); Solver solver = ctx.mkSolver(); solver.add(ctx.mkBVULE(x, ctx.mkBVAdd(y, z))); checkSmall(ctx, solver, x, y, z); } // / Simplifier example. public void simplifierExample(Context ctx) { System.out.println("SimplifierExample"); Log.append("SimplifierExample"); IntExpr x = ctx.mkIntConst("x"); IntExpr y = ctx.mkIntConst("y"); IntExpr z = ctx.mkIntConst("z"); @SuppressWarnings("unused") IntExpr u = ctx.mkIntConst("u"); Expr t1 = ctx.mkAdd(x, ctx.mkSub(y, ctx.mkAdd(x, z))); Expr t2 = t1.simplify(); System.out.println((t1) + " -> " + (t2)); } // / Extract unsatisfiable core example public void unsatCoreAndProofExample(Context ctx) { System.out.println("UnsatCoreAndProofExample"); Log.append("UnsatCoreAndProofExample"); Solver solver = ctx.mkSolver(); BoolExpr pa = ctx.mkBoolConst("PredA"); BoolExpr pb = ctx.mkBoolConst("PredB"); BoolExpr pc = ctx.mkBoolConst("PredC"); BoolExpr pd = ctx.mkBoolConst("PredD"); BoolExpr p1 = ctx.mkBoolConst("P1"); BoolExpr p2 = ctx.mkBoolConst("P2"); BoolExpr p3 = ctx.mkBoolConst("P3"); BoolExpr p4 = ctx.mkBoolConst("P4"); BoolExpr[] assumptions = new BoolExpr[] { ctx.mkNot(p1), ctx.mkNot(p2), ctx.mkNot(p3), ctx.mkNot(p4) }; BoolExpr f1 = ctx.mkAnd(pa, pb, pc); BoolExpr f2 = ctx.mkAnd(pa, ctx.mkNot(pb), pc); BoolExpr f3 = ctx.mkOr(ctx.mkNot(pa), ctx.mkNot(pc)); BoolExpr f4 = pd; solver.add(ctx.mkOr(f1, p1)); solver.add(ctx.mkOr(f2, p2)); solver.add(ctx.mkOr(f3, p3)); solver.add(ctx.mkOr(f4, p4)); Status result = solver.check(assumptions); if (result == Status.UNSATISFIABLE) { System.out.println("unsat"); System.out.println("proof: " + solver.getProof()); System.out.println("core: "); for (Expr c : solver.getUnsatCore()) { System.out.println(c); } } } /// Extract unsatisfiable core example with AssertAndTrack public void unsatCoreAndProofExample2(Context ctx) { System.out.println("UnsatCoreAndProofExample2"); Log.append("UnsatCoreAndProofExample2"); Solver solver = ctx.mkSolver(); BoolExpr pa = ctx.mkBoolConst("PredA"); BoolExpr pb = ctx.mkBoolConst("PredB"); BoolExpr pc = ctx.mkBoolConst("PredC"); BoolExpr pd = ctx.mkBoolConst("PredD"); BoolExpr f1 = ctx.mkAnd(new BoolExpr[] { pa, pb, pc }); BoolExpr f2 = ctx.mkAnd(new BoolExpr[] { pa, ctx.mkNot(pb), pc }); BoolExpr f3 = ctx.mkOr(ctx.mkNot(pa), ctx.mkNot(pc)); BoolExpr f4 = pd; BoolExpr p1 = ctx.mkBoolConst("P1"); BoolExpr p2 = ctx.mkBoolConst("P2"); BoolExpr p3 = ctx.mkBoolConst("P3"); BoolExpr p4 = ctx.mkBoolConst("P4"); solver.assertAndTrack(f1, p1); solver.assertAndTrack(f2, p2); solver.assertAndTrack(f3, p3); solver.assertAndTrack(f4, p4); Status result = solver.check(); if (result == Status.UNSATISFIABLE) { System.out.println("unsat"); System.out.println("core: "); for (Expr c : solver.getUnsatCore()) { System.out.println(c); } } } public void finiteDomainExample(Context ctx) { System.out.println("FiniteDomainExample"); Log.append("FiniteDomainExample"); FiniteDomainSort s = ctx.mkFiniteDomainSort("S", 10); FiniteDomainSort t = ctx.mkFiniteDomainSort("T", 10); FiniteDomainNum s1 = (FiniteDomainNum)ctx.mkNumeral(1, s); FiniteDomainNum t1 = (FiniteDomainNum)ctx.mkNumeral(1, t); System.out.println(s); System.out.println(t); System.out.println(s1); System.out.println(t1); System.out.println(s1.getInt()); System.out.println(t1.getInt()); // But you cannot mix numerals of different sorts // even if the size of their domains are the same: // System.out.println(ctx.mkEq(s1, t1)); } public void floatingPointExample1(Context ctx) throws TestFailedException { System.out.println("FloatingPointExample1"); Log.append("FloatingPointExample1"); FPSort s = ctx.mkFPSort(11, 53); System.out.println("Sort: " + s); FPNum x = (FPNum)ctx.mkNumeral("-1e1", s); /* -1 * 10^1 = -10 */ FPNum y = (FPNum)ctx.mkNumeral("-10", s); /* -10 */ FPNum z = (FPNum)ctx.mkNumeral("-1.25p3", s); /* -1.25 * 2^3 = -1.25 * 8 = -10 */ System.out.println("x=" + x.toString() + "; y=" + y.toString() + "; z=" + z.toString()); BoolExpr a = ctx.mkAnd(ctx.mkFPEq(x, y), ctx.mkFPEq(y, z)); check(ctx, ctx.mkNot(a), Status.UNSATISFIABLE); /* nothing is equal to NaN according to floating-point * equality, so NaN == k should be unsatisfiable. */ FPExpr k = (FPExpr)ctx.mkConst("x", s); FPExpr nan = ctx.mkFPNaN(s); /* solver that runs the default tactic for QF_FP. */ Solver slvr = ctx.mkSolver("QF_FP"); slvr.add(ctx.mkFPEq(nan, k)); if (slvr.check() != Status.UNSATISFIABLE) throw new TestFailedException(); System.out.println("OK, unsat:" + System.getProperty("line.separator") + slvr); /* NaN is equal to NaN according to normal equality. */ slvr = ctx.mkSolver("QF_FP"); slvr.add(ctx.mkEq(nan, nan)); if (slvr.check() != Status.SATISFIABLE) throw new TestFailedException(); System.out.println("OK, sat:" + System.getProperty("line.separator") + slvr); /* Let's prove -1e1 * -1.25e3 == +100 */ x = (FPNum)ctx.mkNumeral("-1e1", s); y = (FPNum)ctx.mkNumeral("-1.25p3", s); FPExpr x_plus_y = (FPExpr)ctx.mkConst("x_plus_y", s); FPNum r = (FPNum)ctx.mkNumeral("100", s); slvr = ctx.mkSolver("QF_FP"); slvr.add(ctx.mkEq(x_plus_y, ctx.mkFPMul(ctx.mkFPRoundNearestTiesToAway(), x, y))); slvr.add(ctx.mkNot(ctx.mkFPEq(x_plus_y, r))); if (slvr.check() != Status.UNSATISFIABLE) throw new TestFailedException(); System.out.println("OK, unsat:" + System.getProperty("line.separator") + slvr); } public void floatingPointExample2(Context ctx) throws TestFailedException { System.out.println("FloatingPointExample2"); Log.append("FloatingPointExample2"); FPSort double_sort = ctx.mkFPSort(11, 53); FPRMSort rm_sort = ctx.mkFPRoundingModeSort(); FPRMExpr rm = (FPRMExpr)ctx.mkConst(ctx.mkSymbol("rm"), rm_sort); BitVecExpr x = (BitVecExpr)ctx.mkConst(ctx.mkSymbol("x"), ctx.mkBitVecSort(64)); FPExpr y = (FPExpr)ctx.mkConst(ctx.mkSymbol("y"), double_sort); FPExpr fp_val = ctx.mkFP(42, double_sort); BoolExpr c1 = ctx.mkEq(y, fp_val); BoolExpr c2 = ctx.mkEq(x, ctx.mkFPToBV(rm, y, 64, false)); BoolExpr c3 = ctx.mkEq(x, ctx.mkBV(42, 64)); BoolExpr c4 = ctx.mkEq(ctx.mkNumeral(42, ctx.getRealSort()), ctx.mkFPToReal(fp_val)); BoolExpr c5 = ctx.mkAnd(c1, c2, c3, c4); System.out.println("c5 = " + c5); /* Generic solver */ Solver s = ctx.mkSolver(); s.add(c5); if (s.check() != Status.SATISFIABLE) throw new TestFailedException(); System.out.println("OK, model: " + s.getModel().toString()); } public void optimizeExample(Context ctx) { System.out.println("Opt"); Optimize opt = ctx.mkOptimize(); // Set constraints. IntExpr xExp = ctx.mkIntConst("x"); IntExpr yExp = ctx.mkIntConst("y"); opt.Add(ctx.mkEq(ctx.mkAdd(xExp, yExp), ctx.mkInt(10)), ctx.mkGe(xExp, ctx.mkInt(0)), ctx.mkGe(yExp, ctx.mkInt(0))); // Set objectives. Optimize.Handle mx = opt.MkMaximize(xExp); Optimize.Handle my = opt.MkMaximize(yExp); System.out.println(opt.Check()); System.out.println(mx); System.out.println(my); } public void translationExample() { Context ctx1 = new Context(); Context ctx2 = new Context(); Sort s1 = ctx1.getIntSort(); Sort s2 = ctx2.getIntSort(); Sort s3 = s1.translate(ctx2); System.out.println(s1 == s2); System.out.println(s1.equals(s2)); System.out.println(s2.equals(s3)); System.out.println(s1.equals(s3)); Expr e1 = ctx1.mkIntConst("e1"); Expr e2 = ctx2.mkIntConst("e1"); Expr e3 = e1.translate(ctx2); System.out.println(e1 == e2); System.out.println(e1.equals(e2)); System.out.println(e2.equals(e3)); System.out.println(e1.equals(e3)); } public void stringExample() { System.out.println("String example"); Context ctx = new Context(); Expr a = ctx.mkToRe(ctx.mkString("abcd")); Expr b = ctx.mkFullRe(ctx.mkReSort(ctx.mkStringSort())); System.out.println(a); System.out.println(b); System.out.println(a.getSort()); System.out.println(b.getSort()); Expr c = ctx.mkConcat(ctx.mkToRe(ctx.mkString("abc")), ctx.mkFullRe(ctx.mkReSort(ctx.mkStringSort())), ctx.mkEmptyRe(ctx.mkReSort(ctx.mkStringSort())), ctx.mkAllcharRe(ctx.mkReSort(ctx.mkStringSort())), ctx.mkToRe(ctx.mkString("d"))); System.out.println(c); } public static void main(String[] args) { JavaExample p = new JavaExample(); try { com.microsoft.z3.Global.ToggleWarningMessages(true); Log.open("test.log"); System.out.print("Z3 Major Version: "); System.out.println(Version.getMajor()); System.out.print("Z3 Full Version: "); System.out.println(Version.getString()); System.out.print("Z3 Full Version String: "); System.out.println(Version.getFullVersion()); p.stringExample(); p.simpleExample(); { // These examples need model generation turned on. HashMap<String, String> cfg = new HashMap<String, String>(); cfg.put("model", "true"); Context ctx = new Context(cfg); p.optimizeExample(ctx); p.basicTests(ctx); p.castingTest(ctx); p.sudokuExample(ctx); p.quantifierExample1(ctx); p.quantifierExample2(ctx); p.logicExample(ctx); p.parOrExample(ctx); p.findModelExample1(ctx); p.findModelExample2(ctx); p.pushPopExample1(ctx); p.arrayExample1(ctx); p.arrayExample3(ctx); p.bitvectorExample1(ctx); p.bitvectorExample2(ctx); p.parserExample1(ctx); p.parserExample2(ctx); p.parserExample5(ctx); p.iteExample(ctx); p.evalExample1(ctx); p.evalExample2(ctx); p.findSmallModelExample(ctx); p.simplifierExample(ctx); p.finiteDomainExample(ctx); p.floatingPointExample1(ctx); // core dumps: p.floatingPointExample2(ctx); } { // These examples need proof generation turned on. HashMap<String, String> cfg = new HashMap<String, String>(); cfg.put("proof", "true"); Context ctx = new Context(cfg); p.proveExample1(ctx); p.proveExample2(ctx); p.arrayExample2(ctx); p.tupleExample(ctx); // throws p.parserExample3(ctx); p.enumExample(ctx); p.listExample(ctx); p.treeExample(ctx); p.forestExample(ctx); p.unsatCoreAndProofExample(ctx); p.unsatCoreAndProofExample2(ctx); } { // These examples need proof generation turned on and auto-config // set to false. HashMap<String, String> cfg = new HashMap<String, String>(); cfg.put("proof", "true"); cfg.put("auto-config", "false"); Context ctx = new Context(cfg); p.quantifierExample3(ctx); p.quantifierExample4(ctx); } p.translationExample(); Log.close(); if (Log.isOpen()) System.out.println("Log is still open!"); } catch (Z3Exception ex) { System.out.println("Z3 Managed Exception: " + ex.getMessage()); System.out.println("Stack trace: "); ex.printStackTrace(System.out); } catch (TestFailedException ex) { System.out.println("TEST CASE FAILED: " + ex.getMessage()); System.out.println("Stack trace: "); ex.printStackTrace(System.out); } catch (Exception ex) { System.out.println("Unknown Exception: " + ex.getMessage()); System.out.println("Stack trace: "); ex.printStackTrace(System.out); } } }
82,384
33.571968
137
java
z3
z3-master/examples/java/JavaGenericExample.java
/*++ Copyright (c) 2012 Microsoft Corporation Module Name: Program.java Abstract: Z3 Java API: Example program Author: Christoph Wintersteiger (cwinter) 2012-11-27 Notes: --*/ import com.microsoft.z3.*; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.util.stream.Stream.concat; class JavaGenericExample { @SuppressWarnings("serial") static class TestFailedException extends Exception { public TestFailedException() { super("Check FAILED"); } } // / Create axiom: function f is injective in the i-th argument. // / <remarks> // / The following axiom is produced: // / <code> // / forall (x_0, ..., x_n) finv(f(x_0, ..., x_i, ..., x_{n-1})) = x_i // / </code> // / Where, <code>finv</code>is a fresh function declaration. public <R extends Sort> BoolExpr injAxiom(Context ctx, FuncDecl<R> f, int i) { Sort[] domain = f.getDomain(); int sz = f.getDomainSize(); if (i >= sz) { System.out.println("failed to create inj axiom"); return null; } /* declare the i-th inverse of f: finv */ Sort finv_domain = f.getRange(); Sort finv_range = domain[i]; FuncDecl<Sort> finv = ctx.mkFuncDecl("f_fresh", finv_domain, finv_range); /* allocate temporary arrays */ /* fill types, names and xs */ Sort[] types = domain.clone(); List<Expr<Sort>> xs = IntStream.range(0, sz).mapToObj(j -> ctx.mkBound(j, types[j])).collect(Collectors.toList()); Symbol[] names = IntStream.range(0, sz).mapToObj(j -> ctx.mkSymbol(String.format("x_%d", j))).toArray(Symbol[]::new); Expr<Sort> x_i = xs.get(i); /* create f(x_0, ..., x_i, ..., x_{n-1}) */ Expr<R> fxs = f.apply(xs.toArray(new Expr[0])); /* create f_inv(f(x_0, ..., x_i, ..., x_{n-1})) */ Expr<Sort> finv_fxs = finv.apply(fxs); /* create finv(f(x_0, ..., x_i, ..., x_{n-1})) = x_i */ BoolExpr eq = ctx.mkEq(finv_fxs, x_i); /* use f(x_0, ..., x_i, ..., x_{n-1}) as the pattern for the quantifier */ Pattern p = ctx.mkPattern(fxs); /* create & assert quantifier */ return ctx.mkForall(types, /* types of quantified variables */ names, /* names of quantified variables */ eq, 1, new Pattern[] { p } /* patterns */, null, null, null); } // / Create axiom: function f is injective in the i-th argument. // / <remarks> // / The following axiom is produced: // / <code> // / forall (x_0, ..., x_n) finv(f(x_0, ..., x_i, ..., x_{n-1})) = x_i // / </code> // / Where, <code>finv</code>is a fresh function declaration. public <R extends Sort> BoolExpr injAxiomAbs(Context ctx, FuncDecl<R> f, int i) { Sort[] domain = f.getDomain(); int sz = f.getDomainSize(); if (i >= sz) { System.out.println("failed to create inj axiom"); return null; } /* declare the i-th inverse of f: finv */ R finv_domain = f.getRange(); Sort finv_range = domain[i]; FuncDecl<Sort> finv = ctx.mkFuncDecl("f_fresh", finv_domain, finv_range); /* allocate temporary arrays */ List<Expr<Sort>> xs = IntStream.range(0, sz).mapToObj(j -> ctx.mkConst(String.format("x_%d", j), domain[j])).collect(Collectors.toList()); /* fill types, names and xs */ Expr<Sort> x_i = xs.get(i); /* create f(x_0, ..., x_i, ..., x_{n-1}) */ Expr<R> fxs = f.apply(xs.toArray(new Expr[0])); /* create f_inv(f(x_0, ..., x_i, ..., x_{n-1})) */ Expr<Sort> finv_fxs = finv.apply(fxs); /* create finv(f(x_0, ..., x_i, ..., x_{n-1})) = x_i */ BoolExpr eq = ctx.mkEq(finv_fxs, x_i); /* use f(x_0, ..., x_i, ..., x_{n-1}) as the pattern for the quantifier */ Pattern p = ctx.mkPattern(fxs); /* create & assert quantifier */ return ctx.mkForall(xs.toArray(new Expr[0]), /* types of quantified variables */ eq, /* names of quantified variables */ 1, new Pattern[] { p } /* patterns */, null, null, null); } // / Assert the axiom: function f is commutative. // / <remarks> // / This example uses the SMT-LIB parser to simplify the axiom // construction. // / </remarks> private <R extends Sort> BoolExpr commAxiom(Context ctx, FuncDecl<R> f) throws Exception { R t = f.getRange(); Sort[] dom = f.getDomain(); if (dom.length != 2 || !t.equals(dom[0]) || !t.equals(dom[1])) { System.out.printf("%d %s %s %s%n", dom.length, dom[0], dom[1], t); throw new Exception("function must be binary, and argument types must be equal to return type"); } String bench = String.format("(assert (forall (x %s) (y %s) (= (%s x y) (%s y x))))", t.getName(), t.getName(), f.getName(), f.getName()); return ctx.parseSMTLIB2String(bench, new Symbol[] { t.getName() }, new Sort[] { t }, new Symbol[] { f.getName() }, new FuncDecl[] { f })[0]; } // / "Hello world" example: create a Z3 logical context, and delete it. public void simpleExample() { System.out.println("SimpleExample"); Log.append("SimpleExample"); { Context ctx = new Context(); /* do something with the context */ /* be kind to dispose manually and not wait for the GC. */ ctx.close(); } } @SuppressWarnings("unchecked") Model check(Context ctx, Expr<BoolSort> f, Status sat) throws TestFailedException { Solver s = ctx.mkSolver(); s.add(f); if (s.check() != sat) throw new TestFailedException(); if (sat == Status.SATISFIABLE) return s.getModel(); else return null; } void solveTactical(Context ctx, Tactic t, Goal g, Status sat) throws TestFailedException { Solver s = ctx.mkSolver(t); System.out.printf("%nTactical solver: %s%n", s); s.add(g.getFormulas()); System.out.printf("Solver: %s%n", s); if (s.check() != sat) throw new TestFailedException(); } ApplyResult applyTactic(Context ctx, Tactic t, Goal g) { System.out.printf("%nGoal: %s%n", g); ApplyResult res = t.apply(g); System.out.printf("Application result: %s%n", res); Status q = Status.UNKNOWN; for (Goal sg : res.getSubgoals()) if (sg.isDecidedSat()) q = Status.SATISFIABLE; else if (sg.isDecidedUnsat()) q = Status.UNSATISFIABLE; switch (q) { case UNKNOWN: System.out.println("Tactic result: Undecided"); break; case SATISFIABLE: System.out.println("Tactic result: SAT"); break; case UNSATISFIABLE: System.out.println("Tactic result: UNSAT"); break; } return res; } void prove(Context ctx, Expr<BoolSort> f, boolean useMBQI) throws TestFailedException { BoolExpr[] assumptions = new BoolExpr[0]; prove(ctx, f, useMBQI, assumptions); } @SafeVarargs final void prove(Context ctx, Expr<BoolSort> f, boolean useMBQI, Expr<BoolSort>... assumptions) throws TestFailedException { System.out.printf("Proving: %s%n", f); Solver s = ctx.mkSolver(); Params p = ctx.mkParams(); p.add("mbqi", useMBQI); s.setParameters(p); s.add(assumptions); s.add(ctx.mkNot(f)); Status q = s.check(); switch (q) { case UNKNOWN: System.out.printf("Unknown because: %s%n", s.getReasonUnknown()); break; case SATISFIABLE: throw new TestFailedException(); case UNSATISFIABLE: System.out.printf("OK, proof: %s%n", s.getProof()); break; } } void disprove(Context ctx, Expr<BoolSort> f, boolean useMBQI) throws TestFailedException { BoolExpr[] a = {}; disprove(ctx, f, useMBQI, a); } @SafeVarargs final void disprove(Context ctx, Expr<BoolSort> f, boolean useMBQI, Expr<BoolSort>... assumptions) throws TestFailedException { System.out.printf("Disproving: %s%n", f); Solver s = ctx.mkSolver(); Params p = ctx.mkParams(); p.add("mbqi", useMBQI); s.setParameters(p); s.add(assumptions); s.add(ctx.mkNot(f)); Status q = s.check(); switch (q) { case UNKNOWN: System.out.printf("Unknown because: %s%n", s.getReasonUnknown()); break; case SATISFIABLE: System.out.printf("OK, model: %s%n", s.getModel()); break; case UNSATISFIABLE: throw new TestFailedException(); } } @SuppressWarnings("unchecked") void modelConverterTest(Context ctx) throws TestFailedException { System.out.println("ModelConverterTest"); Expr<RealSort> xr = ctx.mkConst(ctx.mkSymbol("x"), ctx.mkRealSort()); Expr<RealSort> yr = ctx.mkConst(ctx.mkSymbol("y"), ctx.mkRealSort()); Goal g4 = ctx.mkGoal(true, false, false); g4.add(ctx.mkGt(xr, ctx.mkReal(10, 1))); g4.add(ctx.mkEq(yr, ctx.mkAdd(xr, ctx.mkReal(1, 1)))); g4.add(ctx.mkGt(yr, ctx.mkReal(1, 1))); ApplyResult ar = applyTactic(ctx, ctx.mkTactic("simplify"), g4); if (ar.getNumSubgoals() == 1 && (ar.getSubgoals()[0].isDecidedSat() || ar.getSubgoals()[0] .isDecidedUnsat())) throw new TestFailedException(); ar = applyTactic(ctx, ctx.andThen(ctx.mkTactic("simplify"), ctx.mkTactic("solve-eqs")), g4); if (ar.getNumSubgoals() == 1 && (ar.getSubgoals()[0].isDecidedSat() || ar.getSubgoals()[0] .isDecidedUnsat())) throw new TestFailedException(); Solver s = ctx.mkSolver(); for (BoolExpr e : ar.getSubgoals()[0].getFormulas()) s.add(e); Status q = s.check(); System.out.printf("Solver says: %s%n", q); System.out.printf("Model: %n%s%n", s.getModel()); if (q != Status.SATISFIABLE) throw new TestFailedException(); } // / A simple array example. @SuppressWarnings("unchecked") void arrayExample1(Context ctx) throws TestFailedException { System.out.println("ArrayExample1"); Log.append("ArrayExample1"); Goal g = ctx.mkGoal(true, false, false); ArraySort<IntSort, BitVecSort> asort = ctx.mkArraySort(ctx.getIntSort(), ctx.mkBitVecSort(32)); Expr<ArraySort<IntSort, BitVecSort>> aex = ctx.mkConst(ctx.mkSymbol("MyArray"), asort); Expr<BitVecSort> sel = ctx.mkSelect(aex, ctx.mkInt(0)); g.add(ctx.mkEq(sel, ctx.mkBV(42, 32))); Symbol xs = ctx.mkSymbol("x"); IntExpr xc = (IntExpr) ctx.mkConst(xs, ctx.getIntSort()); Symbol fname = ctx.mkSymbol("f"); Sort[] domain = { ctx.getIntSort() }; FuncDecl<IntSort> fd = ctx.mkFuncDecl(fname, domain, ctx.getIntSort()); Expr<?>[] fargs = { ctx.mkConst(xs, ctx.getIntSort()) }; Expr<IntSort> fapp = ctx.mkApp(fd, fargs); g.add(ctx.mkEq(ctx.mkAdd(xc, fapp), ctx.mkInt(123))); Solver s = ctx.mkSolver(); for (BoolExpr a : g.getFormulas()) s.add(a); System.out.printf("Solver: %s%n", s); Status q = s.check(); System.out.printf("Status: %s%n", q); if (q != Status.SATISFIABLE) throw new TestFailedException(); System.out.printf("Model = %s%n", s.getModel()); System.out.printf("Interpretation of MyArray:%n%s%n", s.getModel().getFuncInterp(aex.getFuncDecl())); System.out.printf("Interpretation of x:%n%s%n", s.getModel().getConstInterp(xc)); System.out.printf("Interpretation of f:%n%s%n", s.getModel().getFuncInterp(fd)); System.out.printf("Interpretation of MyArray as Term:%n%s%n", s.getModel().getFuncInterp(aex.getFuncDecl())); } // / Prove <tt>store(a1, i1, v1) = store(a2, i2, v2) implies (i1 = i3 or i2 // = i3 or select(a1, i3) = select(a2, i3))</tt>. // / <remarks>This example demonstrates how to use the array // theory.</remarks> public void arrayExample2(Context ctx) throws TestFailedException { System.out.println("ArrayExample2"); Log.append("ArrayExample2"); IntSort int_type = ctx.getIntSort(); ArraySort<IntSort, IntSort> array_type = ctx.mkArraySort(int_type, int_type); Expr<ArraySort<IntSort, IntSort>> a1 = ctx.mkConst("a1", array_type); ArrayExpr<IntSort, IntSort> a2 = ctx.mkArrayConst("a2", int_type, int_type); Expr<IntSort> i1 = ctx.mkConst("i1", int_type); Expr<IntSort> i2 = ctx.mkConst("i2", int_type); Expr<IntSort> i3 = ctx.mkConst("i3", int_type); Expr<IntSort> v1 = ctx.mkConst("v1", int_type); Expr<IntSort> v2 = ctx.mkConst("v2", int_type); ArrayExpr<IntSort, IntSort> st1 = ctx.mkStore(a1, i1, v1); ArrayExpr<IntSort, IntSort> st2 = ctx.mkStore(a2, i2, v2); Expr<IntSort> sel1 = ctx.mkSelect(a1, i3); Expr<IntSort> sel2 = ctx.mkSelect(a2, i3); /* create antecedent */ BoolExpr antecedent = ctx.mkEq(st1, st2); /* * create consequent: i1 = i3 or i2 = i3 or select(a1, i3) = select(a2, * i3) */ BoolExpr consequent = ctx.mkOr(ctx.mkEq(i1, i3), ctx.mkEq(i2, i3), ctx.mkEq(sel1, sel2)); /* * prove store(a1, i1, v1) = store(a2, i2, v2) implies (i1 = i3 or i2 = * i3 or select(a1, i3) = select(a2, i3)) */ BoolExpr thm = ctx.mkImplies(antecedent, consequent); System.out.println("prove: store(a1, i1, v1) = store(a2, i2, v2) implies (i1 = i3 or i2 = i3 or select(a1, i3) = select(a2, i3))"); System.out.println(thm); prove(ctx, thm, false); } // / Show that <code>distinct(a_0, ... , a_n)</code> is // / unsatisfiable when <code>a_i</code>'s are arrays from boolean to // / boolean and n > 4. // / <remarks>This example also shows how to use the <code>distinct</code> // construct.</remarks> @SuppressWarnings("unchecked") public void arrayExample3(Context ctx) throws TestFailedException { System.out.println("ArrayExample3"); Log.append("ArrayExample2"); for (int n = 2; n <= 5; n++) { System.out.printf("n = %d%n", n); BoolSort bool_type = ctx.mkBoolSort(); ArraySort<BoolSort, BoolSort> array_type = ctx.mkArraySort(bool_type, bool_type); List<Expr<ArraySort<BoolSort, BoolSort>>> a = IntStream.range(0, n).mapToObj(i -> ctx.mkConst(String.format("array_%d", i), array_type)).collect(Collectors.toList()); /* create arrays */ /* assert distinct(a[0], ..., a[n]) */ BoolExpr d = ctx.mkDistinct(a.toArray(new Expr[0])); System.out.println(d); /* context is satisfiable if n < 5 */ Model model = check(ctx, d, n < 5 ? Status.SATISFIABLE : Status.UNSATISFIABLE); if (n < 5) { for (int i = 0; i < n; i++) { System.out.printf("%s = %s%n", a.get(i), model.evaluate(a.get(i), false)); } } } } // / Sudoku solving example. @SuppressWarnings({"unchecked", "CodeBlock2Expr"}) void sudokuExample(Context ctx) throws TestFailedException { System.out.println("SudokuExample"); Log.append("SudokuExample"); // 9x9 matrix of integer variables List<List<Expr<IntSort>>> X = IntStream.range(0, 9).mapToObj(i -> IntStream.range(0, 9).mapToObj(j -> ctx.mkConst(ctx.mkSymbol(String.format("x_%d_%d", i + 1, j + 1)), ctx.getIntSort())) .collect(Collectors.toList())).collect(Collectors.toList()); // each cell contains a value in {1, ..., 9} List<List<BoolExpr>> cells_c = X.stream().map(r -> r.stream().map(c -> ctx.mkAnd(ctx.mkLe(ctx.mkInt(1), c), ctx.mkLe(c, ctx.mkInt(9)))) .collect(Collectors.toList())).collect(Collectors.toList()); // each row contains a digit at most once List<BoolExpr> rows_c = new ArrayList<>(); for (int i1 = 0; i1 < 9; i1++) { BoolExpr boolExpr = ctx.mkDistinct(X.get(i1).toArray(new Expr[0])); rows_c.add(boolExpr); } // each column contains a digit at most once List<BoolExpr> cols_c = new ArrayList<>(); for (int idx = 0; idx < 9; idx++) { int j1 = idx; BoolExpr boolExpr = ctx.mkDistinct(X.stream().map(r -> r.get(j1)).toArray(Expr[]::new)); cols_c.add(boolExpr); } // each 3x3 square contains a digit at most once List<List<BoolExpr>> sq_c = new ArrayList<>(); for (int i0 = 0; i0 < 3; i0++) { List<BoolExpr> collect = new ArrayList<>(); for (int j0 = 0; j0 < 3; j0++) { List<Expr<IntSort>> list = new ArrayList<>(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Expr<IntSort> intSortExpr = X.get(3 * i0 + i).get(3 * j0 + j); list.add(intSortExpr); } } BoolExpr boolExpr = ctx.mkDistinct(list.toArray(new Expr[0])); collect.add(boolExpr); } sq_c.add(collect); } Stream<BoolExpr> sudoku_s = cells_c.stream().flatMap(Collection::stream); sudoku_s = concat(sudoku_s, rows_c.stream()); sudoku_s = concat(sudoku_s, cols_c.stream()); sudoku_s = concat(sudoku_s, sq_c.stream().flatMap(Collection::stream)); BoolExpr sudoku_c = ctx.mkAnd(sudoku_s.toArray(BoolExpr[]::new)); // sudoku instance, we use '0' for empty cells int[][] instance = { { 0, 0, 0, 0, 9, 4, 0, 3, 0 }, { 0, 0, 0, 5, 1, 0, 0, 0, 7 }, { 0, 8, 9, 0, 0, 0, 0, 4, 0 }, { 0, 0, 0, 0, 0, 0, 2, 0, 8 }, { 0, 6, 0, 2, 0, 1, 0, 5, 0 }, { 1, 0, 2, 0, 0, 0, 0, 0, 0 }, { 0, 7, 0, 0, 0, 0, 5, 2, 0 }, { 9, 0, 0, 0, 6, 5, 0, 0, 0 }, { 0, 4, 0, 9, 7, 0, 0, 0, 0 } }; // assert the variables we know BoolExpr instance_c = ctx.mkAnd(IntStream.range(0, 9).boxed().flatMap(i -> IntStream.range(0, 9).filter(j -> instance[i][j] != 0).mapToObj(j -> ctx.mkEq(X.get(i).get(j), ctx.mkInt(instance[i][j])))).toArray(Expr[]::new)); Solver s = ctx.mkSolver(); s.add(sudoku_c); s.add(instance_c); if (s.check() == Status.SATISFIABLE) { Model m = s.getModel(); List<List<Expr<IntSort>>> R = X.stream().map(r -> r.stream().map(c -> m.eval(c, false)).collect(Collectors.toList())).collect(Collectors.toList()); System.out.println("Sudoku solution:"); R.forEach(r -> System.out.println(r.stream().map(Objects::toString).collect(Collectors.joining(" ")))); } else { System.out.println("Failed to solve sudoku"); throw new TestFailedException(); } } // / A basic example of how to use quantifiers. @SuppressWarnings("unchecked") void quantifierExample1(Context ctx) { System.out.println("QuantifierExample"); Log.append("QuantifierExample"); IntSort[] types = new IntSort[3]; Arrays.fill(types, ctx.getIntSort()); Symbol[] names = IntStream.range(0, 3).mapToObj(j -> ctx.mkSymbol(String.format("x_%d", j))).toArray(Symbol[]::new); List<Expr<IntSort>> xs = IntStream.range(0, 3).mapToObj(j -> ctx.mkConst(names[j], types[j])).collect(Collectors.toList()); List<Expr<IntSort>> vars = IntStream.range(0, 3).mapToObj(j -> ctx.mkBound(2 - j, types[j])).collect(Collectors.toList()); BoolExpr body_vars = ctx.mkAnd( ctx.mkEq(ctx.mkAdd(vars.get(0), ctx.mkInt(1)), ctx.mkInt(2)), ctx.mkEq(ctx.mkAdd(vars.get(1), ctx.mkInt(2)), ctx.mkAdd(vars.get(2), ctx.mkInt(3)))); BoolExpr body_const = ctx.mkAnd( ctx.mkEq(ctx.mkAdd(xs.get(0), ctx.mkInt(1)), ctx.mkInt(2)), ctx.mkEq(ctx.mkAdd(xs.get(1), ctx.mkInt(2)), ctx.mkAdd(xs.get(2), ctx.mkInt(3)))); Quantifier x = ctx.mkForall(types, names, body_vars, 1, null, null, ctx.mkSymbol("Q1"), ctx.mkSymbol("skid1")); System.out.printf("Quantifier X: %s%n", x.toString()); Quantifier y = ctx.mkForall(xs.toArray(new Expr[0]), body_const, 1, null, null, ctx.mkSymbol("Q2"), ctx.mkSymbol("skid2")); System.out.printf("Quantifier Y: %s%n", y.toString()); } void quantifierExample2(Context ctx) { System.out.println("QuantifierExample2"); Log.append("QuantifierExample2"); Quantifier q1, q2; FuncDecl<IntSort> f = ctx.mkFuncDecl("f", ctx.getIntSort(), ctx.getIntSort()); FuncDecl<IntSort> g = ctx.mkFuncDecl("g", ctx.getIntSort(), ctx.getIntSort()); // Quantifier with Exprs as the bound variables. { Expr<IntSort> x = ctx.mkConst("x", ctx.getIntSort()); Expr<IntSort> y = ctx.mkConst("y", ctx.getIntSort()); Expr<IntSort> f_x = ctx.mkApp(f, x); Expr<IntSort> f_y = ctx.mkApp(f, y); Expr<IntSort> g_y = ctx.mkApp(g, y); @SuppressWarnings("unused") Pattern[] pats = new Pattern[] { ctx.mkPattern(f_x, g_y) }; Expr[] no_pats = new Expr[] { f_y }; Expr[] bound = new Expr[] { x, y }; BoolExpr body = ctx.mkAnd(ctx.mkEq(f_x, f_y), ctx.mkEq(f_y, g_y)); q1 = ctx.mkForall(bound, body, 1, null, no_pats, ctx.mkSymbol("q"), ctx.mkSymbol("sk")); System.out.println(q1); } // Quantifier with de-Bruijn indices. { Expr<IntSort> x = ctx.mkBound(1, ctx.getIntSort()); Expr<IntSort> y = ctx.mkBound(0, ctx.getIntSort()); Expr<IntSort> f_x = ctx.mkApp(f, x); Expr<IntSort> f_y = ctx.mkApp(f, y); Expr<IntSort> g_y = ctx.mkApp(g, y); @SuppressWarnings("unused") Pattern[] pats = new Pattern[] { ctx.mkPattern(f_x, g_y) }; Expr[] no_pats = new Expr[] { f_y }; Symbol[] names = new Symbol[] { ctx.mkSymbol("x"), ctx.mkSymbol("y") }; Sort[] sorts = new Sort[] { ctx.getIntSort(), ctx.getIntSort() }; BoolExpr body = ctx.mkAnd(ctx.mkEq(f_x, f_y), ctx.mkEq(f_y, g_y)); q2 = ctx.mkForall(sorts, names, body, 1, null, // pats, no_pats, ctx.mkSymbol("q"), ctx.mkSymbol("sk")); System.out.println(q2); } System.out.println(q1.equals(q2)); } // / Prove that <tt>f(x, y) = f(w, v) implies y = v</tt> when // / <code>f</code> is injective in the second argument. <seealso // cref="inj_axiom"/> public void quantifierExample3(Context ctx) throws TestFailedException { System.out.println("QuantifierExample3"); Log.append("QuantifierExample3"); /* * If quantified formulas are asserted in a logical context, then the * model produced by Z3 should be viewed as a potential model. */ /* declare function f */ IntSort I = ctx.getIntSort(); FuncDecl<IntSort> f = ctx.mkFuncDecl("f", new Sort[] { I, I }, I); /* f is injective in the second argument. */ BoolExpr inj = injAxiom(ctx, f, 1); /* create x, y, v, w, fxy, fwv */ IntExpr x = ctx.mkIntConst("x"); IntExpr y = ctx.mkIntConst("y"); IntExpr v = ctx.mkIntConst("v"); IntExpr w = ctx.mkIntConst("w"); Expr<IntSort> fxy = ctx.mkApp(f, x, y); Expr<IntSort> fwv = ctx.mkApp(f, w, v); /* f(x, y) = f(w, v) */ BoolExpr p1 = ctx.mkEq(fxy, fwv); /* prove f(x, y) = f(w, v) implies y = v */ BoolExpr p2 = ctx.mkEq(y, v); prove(ctx, p2, false, inj, p1); /* disprove f(x, y) = f(w, v) implies x = w */ BoolExpr p3 = ctx.mkEq(x, w); disprove(ctx, p3, false, inj, p1); } // / Prove that <tt>f(x, y) = f(w, v) implies y = v</tt> when // / <code>f</code> is injective in the second argument. <seealso // cref="inj_axiom"/> public void quantifierExample4(Context ctx) throws TestFailedException { System.out.println("QuantifierExample4"); Log.append("QuantifierExample4"); /* * If quantified formulas are asserted in a logical context, then the * model produced by Z3 should be viewed as a potential model. */ /* declare function f */ IntSort I = ctx.getIntSort(); FuncDecl<IntSort> f = ctx.mkFuncDecl("f", new Sort[] { I, I }, I); /* f is injective in the second argument. */ BoolExpr inj = injAxiomAbs(ctx, f, 1); /* create x, y, v, w, fxy, fwv */ IntExpr x = ctx.mkIntConst("x"); IntExpr y = ctx.mkIntConst("y"); IntExpr v = ctx.mkIntConst("v"); IntExpr w = ctx.mkIntConst("w"); Expr<IntSort> fxy = ctx.mkApp(f, x, y); Expr<IntSort> fwv = ctx.mkApp(f, w, v); /* f(x, y) = f(w, v) */ BoolExpr p1 = ctx.mkEq(fxy, fwv); /* prove f(x, y) = f(w, v) implies y = v */ BoolExpr p2 = ctx.mkEq(y, v); prove(ctx, p2, false, inj, p1); /* disprove f(x, y) = f(w, v) implies x = w */ BoolExpr p3 = ctx.mkEq(x, w); disprove(ctx, p3, false, inj, p1); } // / Some basic tests. void basicTests(Context ctx) throws TestFailedException { System.out.println("BasicTests"); Symbol fname = ctx.mkSymbol("f"); Symbol x = ctx.mkSymbol("x"); Symbol y = ctx.mkSymbol("y"); BoolSort bs = ctx.mkBoolSort(); Sort[] domain = { bs, bs }; FuncDecl<BoolSort> f = ctx.mkFuncDecl(fname, domain, bs); Expr<BoolSort> fapp = ctx.mkApp(f, ctx.mkConst(x, bs), ctx.mkConst(y, bs)); Expr<?>[] fargs2 = { ctx.mkFreshConst("cp", bs) }; Sort[] domain2 = { bs }; Expr<BoolSort> fapp2 = ctx.mkApp(ctx.mkFreshFuncDecl("fp", domain2, bs), fargs2); BoolExpr trivial_eq = ctx.mkEq(fapp, fapp); BoolExpr nontrivial_eq = ctx.mkEq(fapp, fapp2); Goal g = ctx.mkGoal(true, false, false); g.add(trivial_eq); g.add(nontrivial_eq); System.out.printf("Goal: %s%n", g); Solver solver = ctx.mkSolver(); solver.add(g.getFormulas()); if (solver.check() != Status.SATISFIABLE) throw new TestFailedException(); ApplyResult ar = applyTactic(ctx, ctx.mkTactic("simplify"), g); if (ar.getNumSubgoals() == 1 && (ar.getSubgoals()[0].isDecidedSat() || ar.getSubgoals()[0] .isDecidedUnsat())) throw new TestFailedException(); ar = applyTactic(ctx, ctx.mkTactic("smt"), g); if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedSat()) throw new TestFailedException(); g.add(ctx.mkEq(ctx.mkNumeral(1, ctx.mkBitVecSort(32)), ctx.mkNumeral(2, ctx.mkBitVecSort(32)))); ar = applyTactic(ctx, ctx.mkTactic("smt"), g); if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedUnsat()) throw new TestFailedException(); Goal g2 = ctx.mkGoal(true, true, false); ar = applyTactic(ctx, ctx.mkTactic("smt"), g2); if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedSat()) throw new TestFailedException(); g2 = ctx.mkGoal(true, true, false); g2.add(ctx.mkFalse()); ar = applyTactic(ctx, ctx.mkTactic("smt"), g2); if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedUnsat()) throw new TestFailedException(); Goal g3 = ctx.mkGoal(true, true, false); Expr<IntSort> xc = ctx.mkConst(ctx.mkSymbol("x"), ctx.getIntSort()); Expr<IntSort> yc = ctx.mkConst(ctx.mkSymbol("y"), ctx.getIntSort()); g3.add(ctx.mkEq(xc, ctx.mkNumeral(1, ctx.getIntSort()))); g3.add(ctx.mkEq(yc, ctx.mkNumeral(2, ctx.getIntSort()))); BoolExpr constr = ctx.mkEq(xc, yc); g3.add(constr); ar = applyTactic(ctx, ctx.mkTactic("smt"), g3); if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedUnsat()) throw new TestFailedException(); modelConverterTest(ctx); // Real num/den test. RatNum rn = ctx.mkReal(42, 43); IntNum inum = rn.getNumerator(); IntNum iden = rn.getDenominator(); System.out.printf("Numerator: %s Denominator: %s%n", inum, iden); if (!inum.toString().equals("42") || !iden.toString().equals("43")) throw new TestFailedException(); if (!rn.toDecimalString(3).equals("0.976?")) throw new TestFailedException(); bigIntCheck(ctx, ctx.mkReal("-1231231232/234234333")); bigIntCheck(ctx, ctx.mkReal("-123123234234234234231232/234234333")); bigIntCheck(ctx, ctx.mkReal("-234234333")); bigIntCheck(ctx, ctx.mkReal("234234333/2")); String bn = "1234567890987654321"; if (!ctx.mkInt(bn).getBigInteger().toString().equals(bn)) throw new TestFailedException(); if (!ctx.mkBV(bn, 128).getBigInteger().toString().equals(bn)) throw new TestFailedException(); if (ctx.mkBV(bn, 32).getBigInteger().toString().equals(bn)) throw new TestFailedException(); // Error handling test. try { @SuppressWarnings("unused") IntExpr i = ctx.mkInt("1/2"); throw new TestFailedException(); // unreachable } catch (Z3Exception ignored) { } // Coercing type change in Z3 Expr<IntSort> integerDivision = ctx.mkDiv(ctx.mkInt(1), ctx.mkInt(2)); System.out.printf("%s -> %s%n", integerDivision, integerDivision.simplify()); // (div 1 2) -> 0 Expr<RealSort> realDivision = ctx.mkDiv(ctx.mkReal(1), ctx.mkReal(2)); System.out.printf("%s -> %s%n", realDivision, realDivision.simplify()); // (/ 1.0 2.0) -> 1/2 Expr<ArithSort> mixedDivision1 = ctx.mkDiv(ctx.mkReal(1), ctx.mkInt(2)); Expr<ArithSort> tmp = mixedDivision1; // the return type is a Expr<ArithSort> here but since we know it is a // real view it as such. Expr<RealSort> mixedDivision2 = mixedDivision1.distillSort(RealSort.class); System.out.printf("%s -> %s%n", mixedDivision2, mixedDivision2.simplify()); // (/ 1.0 (to_real 2)) -> 1/2 // empty distillSort mixedDivision1.distillSort(ArithSort.class); try { mixedDivision1.distillSort(IntSort.class); throw new TestFailedException(); // unreachable } catch (Z3Exception exception) { System.out.println(exception); // com.microsoft.z3.Z3Exception: Cannot cast expression of sort // com.microsoft.z3.RealSort to com.microsoft.z3.IntSort. } Expr<BoolSort> eq1 = ctx.mkEq(realDivision, integerDivision); System.out.printf("%s -> %s%n", eq1, eq1.simplify()); // (= (/ 1.0 2.0) (to_real (div 1 2))) -> false Expr<BoolSort> eq2 = ctx.mkEq(realDivision, mixedDivision2); System.out.printf("%s -> %s%n", eq2, eq2.simplify()); // (= (/ 1.0 2.0) (/ 1.0 (to_real 2))) -> true } // / Shows how to use Solver(logic) // / @param ctx void logicExample(Context ctx) throws TestFailedException { System.out.println("LogicTest"); Log.append("LogicTest"); Global.ToggleWarningMessages(true); BitVecSort bvs = ctx.mkBitVecSort(32); Expr<BitVecSort> x = ctx.mkConst("x", bvs); Expr<BitVecSort> y = ctx.mkConst("y", bvs); BoolExpr eq = ctx.mkEq(x, y); // Use a solver for QF_BV Solver s = ctx.mkSolver("QF_BV"); s.add(eq); Status res = s.check(); System.out.printf("solver result: %s%n", res); // Or perhaps a tactic for QF_BV Goal g = ctx.mkGoal(true, false, false); g.add(eq); Tactic t = ctx.mkTactic("qfbv"); ApplyResult ar = t.apply(g); System.out.printf("tactic result: %s%n", ar); if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedSat()) throw new TestFailedException(); } // / Demonstrates how to use the ParOr tactic. void parOrExample(Context ctx) throws TestFailedException { System.out.println("ParOrExample"); Log.append("ParOrExample"); BitVecSort bvs = ctx.mkBitVecSort(32); Expr<BitVecSort> x = ctx.mkConst("x", bvs); Expr<BitVecSort> y = ctx.mkConst("y", bvs); BoolExpr q = ctx.mkEq(x, y); Goal g = ctx.mkGoal(true, false, false); g.add(q); Tactic t1 = ctx.mkTactic("qfbv"); Tactic t2 = ctx.mkTactic("qfbv"); Tactic p = ctx.parOr(t1, t2); ApplyResult ar = p.apply(g); if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedSat()) throw new TestFailedException(); } void bigIntCheck(Context ctx, RatNum r) { System.out.printf("Num: %s%n", r.getBigIntNumerator()); System.out.printf("Den: %s%n", r.getBigIntDenominator()); } // / Find a model for <code>x xor y</code>. public void findModelExample1(Context ctx) throws TestFailedException { System.out.println("FindModelExample1"); Log.append("FindModelExample1"); BoolExpr x = ctx.mkBoolConst("x"); BoolExpr y = ctx.mkBoolConst("y"); BoolExpr x_xor_y = ctx.mkXor(x, y); Model model = check(ctx, x_xor_y, Status.SATISFIABLE); System.out.printf("x = %s, y = %s%n", model.evaluate(x, false), model.evaluate(y, false)); } // / Find a model for <tt>x < y + 1, x > 2</tt>. // / Then, assert <tt>not(x = y)</tt>, and find another model. public void findModelExample2(Context ctx) throws TestFailedException { System.out.println("FindModelExample2"); Log.append("FindModelExample2"); IntExpr x = ctx.mkIntConst("x"); IntExpr y = ctx.mkIntConst("y"); IntNum one = ctx.mkInt(1); IntNum two = ctx.mkInt(2); ArithExpr<IntSort> y_plus_one = ctx.mkAdd(y, one); BoolExpr c1 = ctx.mkLt(x, y_plus_one); BoolExpr c2 = ctx.mkGt(x, two); BoolExpr q = ctx.mkAnd(c1, c2); System.out.println("model for: x < y + 1, x > 2"); Model model = check(ctx, q, Status.SATISFIABLE); System.out.printf("x = %s, y =%s%n", model.evaluate(x, false), model.evaluate(y, false)); /* assert not(x = y) */ BoolExpr x_eq_y = ctx.mkEq(x, y); BoolExpr c3 = ctx.mkNot(x_eq_y); q = ctx.mkAnd(q, c3); System.out.println("model for: x < y + 1, x > 2, not(x = y)"); model = check(ctx, q, Status.SATISFIABLE); System.out.printf("x = %s, y = %s%n", model.evaluate(x, false), model.evaluate(y, false)); } // / Prove <tt>x = y implies g(x) = g(y)</tt>, and // / disprove <tt>x = y implies g(g(x)) = g(y)</tt>. // / <remarks>This function demonstrates how to create uninterpreted // / types and functions.</remarks> public void proveExample1(Context ctx) throws TestFailedException { System.out.println("ProveExample1"); Log.append("ProveExample1"); /* create uninterpreted type. */ UninterpretedSort U = ctx.mkUninterpretedSort(ctx.mkSymbol("U")); /* declare function g */ FuncDecl<UninterpretedSort> g = ctx.mkFuncDecl("g", U, U); /* create x and y */ Expr<UninterpretedSort> x = ctx.mkConst("x", U); Expr<UninterpretedSort> y = ctx.mkConst("y", U); /* create g(x), g(y) */ Expr<UninterpretedSort> gx = g.apply(x); Expr<UninterpretedSort> gy = g.apply(y); /* assert x = y */ BoolExpr eq = ctx.mkEq(x, y); /* prove g(x) = g(y) */ BoolExpr f = ctx.mkEq(gx, gy); System.out.println("prove: x = y implies g(x) = g(y)"); prove(ctx, ctx.mkImplies(eq, f), false); /* create g(g(x)) */ Expr<UninterpretedSort> ggx = g.apply(gx); /* disprove g(g(x)) = g(y) */ f = ctx.mkEq(ggx, gy); System.out.println("disprove: x = y implies g(g(x)) = g(y)"); disprove(ctx, ctx.mkImplies(eq, f), false); /* Print the model using the custom model printer */ Model m = check(ctx, ctx.mkNot(f), Status.SATISFIABLE); System.out.println(m); } // / Prove <tt>not(g(g(x) - g(y)) = g(z)), x + z <= y <= x implies z < 0 // </tt>. // / Then, show that <tt>z < -1</tt> is not implied. // / <remarks>This example demonstrates how to combine uninterpreted // functions // / and arithmetic.</remarks> public void proveExample2(Context ctx) throws TestFailedException { System.out.println("ProveExample2"); Log.append("ProveExample2"); /* declare function g */ IntSort I = ctx.getIntSort(); FuncDecl<IntSort> g = ctx.mkFuncDecl("g", I, I); /* create x, y, and z */ IntExpr x = ctx.mkIntConst("x"); IntExpr y = ctx.mkIntConst("y"); IntExpr z = ctx.mkIntConst("z"); /* create gx, gy, gz */ Expr<IntSort> gx = ctx.mkApp(g, x); Expr<IntSort> gy = ctx.mkApp(g, y); Expr<IntSort> gz = ctx.mkApp(g, z); /* create zero */ IntNum zero = ctx.mkInt(0); /* assert not(g(g(x) - g(y)) = g(z)) */ ArithExpr<IntSort> gx_gy = ctx.mkSub(gx, gy); Expr<IntSort> ggx_gy = ctx.mkApp(g, gx_gy); BoolExpr eq = ctx.mkEq(ggx_gy, gz); BoolExpr c1 = ctx.mkNot(eq); /* assert x + z <= y */ ArithExpr<IntSort> x_plus_z = ctx.mkAdd(x, z); BoolExpr c2 = ctx.mkLe(x_plus_z, y); /* assert y <= x */ BoolExpr c3 = ctx.mkLe(y, x); /* prove z < 0 */ BoolExpr f = ctx.mkLt(z, zero); System.out.println("prove: not(g(g(x) - g(y)) = g(z)), x + z <= y <= x implies z < 0"); prove(ctx, f, false, c1, c2, c3); /* disprove z < -1 */ IntNum minus_one = ctx.mkInt(-1); f = ctx.mkLt(z, minus_one); System.out.println("disprove: not(g(g(x) - g(y)) = g(z)), x + z <= y <= x implies z < -1"); disprove(ctx, f, false, c1, c2, c3); } // / Show how push & pop can be used to create "backtracking" points. // / <remarks>This example also demonstrates how big numbers can be // / created in ctx.</remarks> public void pushPopExample1(Context ctx) throws TestFailedException { System.out.println("PushPopExample1"); Log.append("PushPopExample1"); /* create a big number */ IntSort int_type = ctx.getIntSort(); IntNum big_number = ctx.mkInt("1000000000000000000000000000000000000000000000000000000"); /* create number 3 */ IntExpr three = (IntExpr) ctx.mkNumeral("3", int_type); /* create x */ IntExpr x = ctx.mkIntConst("x"); Solver solver = ctx.mkSolver(); /* assert x >= "big number" */ BoolExpr c1 = ctx.mkGe(x, big_number); System.out.println("assert: x >= 'big number'"); solver.add(c1); /* create a backtracking point */ System.out.println("push"); solver.push(); /* assert x <= 3 */ BoolExpr c2 = ctx.mkLe(x, three); System.out.println("assert: x <= 3"); solver.add(c2); /* context is inconsistent at this point */ if (solver.check() != Status.UNSATISFIABLE) throw new TestFailedException(); /* * backtrack: the constraint x <= 3 will be removed, since it was * asserted after the last ctx.Push. */ System.out.println("pop"); solver.pop(1); /* the context is consistent again. */ if (solver.check() != Status.SATISFIABLE) throw new TestFailedException(); /* new constraints can be asserted... */ /* create y */ IntExpr y = ctx.mkIntConst("y"); /* assert y > x */ BoolExpr c3 = ctx.mkGt(y, x); System.out.println("assert: y > x"); solver.add(c3); /* the context is still consistent. */ if (solver.check() != Status.SATISFIABLE) throw new TestFailedException(); } // / Tuples. // / <remarks>Check that the projection of a tuple // / returns the corresponding element.</remarks> public void tupleExample(Context ctx) throws TestFailedException { System.out.println("TupleExample"); Log.append("TupleExample"); IntSort int_type = ctx.getIntSort(); TupleSort tuple = ctx.mkTupleSort(ctx.mkSymbol("mk_tuple"), // name of // tuple // constructor new Symbol[] { ctx.mkSymbol("first"), ctx.mkSymbol("second") }, // names // of // projection // operators new Sort[] { int_type, int_type } // types of projection // operators ); // have to cast here because it is not possible to type a member of an array of mixed generics @SuppressWarnings("unchecked") FuncDecl<IntSort> first = (FuncDecl<IntSort>) tuple.getFieldDecls()[0]; // declarations are for // projections @SuppressWarnings("unused") FuncDecl<?> second = tuple.getFieldDecls()[1]; Expr<IntSort> x = ctx.mkConst("x", int_type); Expr<IntSort> y = ctx.mkConst("y", int_type); Expr<TupleSort> n1 = tuple.mkDecl().apply(x, y); Expr<IntSort> n2 = first.apply(n1); BoolExpr n3 = ctx.mkEq(x, n2); System.out.printf("Tuple example: %s%n", n3); prove(ctx, n3, false); } // / Simple bit-vector example. // / <remarks> // / This example disproves that x - 10 &lt;= 0 IFF x &lt;= 10 for (32-bit) // machine integers // / </remarks> public void bitvectorExample1(Context ctx) throws TestFailedException { System.out.println("BitvectorExample1"); Log.append("BitvectorExample1"); BitVecSort bv_type = ctx.mkBitVecSort(32); Expr<BitVecSort> x = ctx.mkConst("x", bv_type); Expr<BitVecSort> zero = ctx.mkNumeral("0", bv_type); BitVecNum ten = ctx.mkBV(10, 32); BitVecExpr x_minus_ten = ctx.mkBVSub(x, ten); /* bvsle is signed less than or equal to */ BoolExpr c1 = ctx.mkBVSLE(x, ten); BoolExpr c2 = ctx.mkBVSLE(x_minus_ten, zero); BoolExpr thm = ctx.mkIff(c1, c2); System.out.println("disprove: x - 10 <= 0 IFF x <= 10 for (32-bit) machine integers"); disprove(ctx, thm, false); } // / Find x and y such that: x ^ y - 103 == x * y public void bitvectorExample2(Context ctx) throws TestFailedException { System.out.println("BitvectorExample2"); Log.append("BitvectorExample2"); /* construct x ^ y - 103 == x * y */ BitVecSort bv_type = ctx.mkBitVecSort(32); BitVecExpr x = ctx.mkBVConst("x", 32); BitVecExpr y = ctx.mkBVConst("y", 32); BitVecExpr x_xor_y = ctx.mkBVXOR(x, y); Expr<BitVecSort> c103 = ctx.mkNumeral("103", bv_type); BitVecExpr lhs = ctx.mkBVSub(x_xor_y, c103); BitVecExpr rhs = ctx.mkBVMul(x, y); BoolExpr ctr = ctx.mkEq(lhs, rhs); System.out.println("find values of x and y, such that x ^ y - 103 == x * y"); /* find a model (i.e., values for x an y that satisfy the constraint */ Model m = check(ctx, ctr, Status.SATISFIABLE); System.out.println(m); } // / Demonstrates how to use the SMTLIB parser. public void parserExample1(Context ctx) throws TestFailedException { System.out.println("ParserExample1"); Log.append("ParserExample1"); BoolExpr f = ctx.parseSMTLIB2String( "(declare-const x Int) (declare-const y Int) (assert (and (> x y) (> x 0)))", null, null, null, null)[0]; System.out.printf("formula %s%n", f); @SuppressWarnings("unused") Model m = check(ctx, f, Status.SATISFIABLE); } // / Demonstrates how to initialize the parser symbol table. public void parserExample2(Context ctx) throws TestFailedException { System.out.println("ParserExample2"); Log.append("ParserExample2"); Symbol[] declNames = { ctx.mkSymbol("a"), ctx.mkSymbol("b") }; FuncDecl<IntSort> a = ctx.mkConstDecl(declNames[0], ctx.mkIntSort()); FuncDecl<IntSort> b = ctx.mkConstDecl(declNames[1], ctx.mkIntSort()); FuncDecl[] decls = new FuncDecl[] { a, b }; BoolExpr f = ctx.parseSMTLIB2String("(assert (> a b))", null, null, declNames, decls)[0]; System.out.printf("formula: %s%n", f); check(ctx, f, Status.SATISFIABLE); } // / Demonstrates how to initialize the parser symbol table. public void parserExample3(Context ctx) throws Exception { System.out.println("ParserExample3"); Log.append("ParserExample3"); /* declare function g */ IntSort I = ctx.mkIntSort(); FuncDecl<IntSort> g = ctx.mkFuncDecl("g", new Sort[] { I, I }, I); BoolExpr ca = commAxiom(ctx, g); BoolExpr thm = ctx.parseSMTLIB2String( "(declare-fun (Int Int) Int) (assert (forall ((x Int) (y Int)) (=> (= x y) (= (gg x 0) (gg 0 y)))))", null, null, new Symbol[] { ctx.mkSymbol("gg") }, new FuncDecl[] { g })[0]; System.out.printf("formula: %s%n", thm); prove(ctx, thm, false, ca); } // / Demonstrates how to handle parser errors using Z3 error handling // support. // / <remarks></remarks> public void parserExample5(Context ctx) { System.out.println("ParserExample5"); try { ctx.parseSMTLIB2String( /* * the following string has a parsing error: missing * parenthesis */ "(declare-const x Int (declare-const y Int)) (assert (> x y))", null, null, null, null); } catch (Z3Exception e) { System.out.printf("Z3 error: %s%n", e); } } // / Create an ite-Expr (if-then-else Exprs). public void iteExample(Context ctx) { System.out.println("ITEExample"); Log.append("ITEExample"); BoolExpr f = ctx.mkFalse(); IntNum one = ctx.mkInt(1); IntNum zero = ctx.mkInt(0); Expr<IntSort> ite = ctx.mkITE(f, one, zero); System.out.printf("Expr: %s%n", ite); } // / Create an enumeration data type. public <T extends Sort> void enumExampleTyped(Context ctx) throws TestFailedException { System.out.println("EnumExample"); Log.append("EnumExample"); Symbol name = ctx.mkSymbol("fruit"); EnumSort<T> fruit = ctx.mkEnumSort(name, ctx.mkSymbol("apple"), ctx.mkSymbol("banana"), ctx.mkSymbol("orange")); // helper function for consistent typing: https://docs.oracle.com/javase/tutorial/java/generics/capture.html System.out.println((fruit.getConsts()[0])); System.out.println((fruit.getConsts()[1])); System.out.println((fruit.getConsts()[2])); System.out.println((fruit.getTesterDecls()[0])); System.out.println((fruit.getTesterDecls()[1])); System.out.println((fruit.getTesterDecls()[2])); Expr<EnumSort<T>> apple = fruit.getConsts()[0]; Expr<EnumSort<T>> banana = fruit.getConsts()[1]; Expr<EnumSort<T>> orange = fruit.getConsts()[2]; /* Apples are different from oranges */ prove(ctx, ctx.mkNot(ctx.mkEq(apple, orange)), false); /* Apples pass the apple test */ prove(ctx, ctx.mkApp(fruit.getTesterDecls()[0], apple), false); /* Oranges fail the apple test */ disprove(ctx, ctx.mkApp(fruit.getTesterDecls()[0], orange), false); prove(ctx, ctx.mkNot(ctx.mkApp(fruit.getTesterDecls()[0], orange)), false); Expr<EnumSort<T>> fruity = ctx.mkConst("fruity", fruit); /* If something is fruity, then it is an apple, banana, or orange */ prove(ctx, ctx.mkOr(ctx.mkEq(fruity, apple), ctx.mkEq(fruity, banana), ctx.mkEq(fruity, orange)), false); } // while you can do this untyped, it's safer to have a helper function -- this will prevent you from // mixing up your enum types public void enumExampleUntyped(Context ctx) throws TestFailedException { System.out.println("EnumExample"); Log.append("EnumExample"); Symbol name = ctx.mkSymbol("fruit"); EnumSort<Object> fruit = ctx.mkEnumSort(name, ctx.mkSymbol("apple"), ctx.mkSymbol("banana"), ctx.mkSymbol("orange")); System.out.println((fruit.getConsts()[0])); System.out.println((fruit.getConsts()[1])); System.out.println((fruit.getConsts()[2])); System.out.println((fruit.getTesterDecls()[0])); System.out.println((fruit.getTesterDecls()[1])); System.out.println((fruit.getTesterDecls()[2])); Expr<EnumSort<Object>> apple = fruit.getConsts()[0]; Expr<EnumSort<Object>> banana = fruit.getConsts()[1]; Expr<EnumSort<Object>> orange = fruit.getConsts()[2]; /* Apples are different from oranges */ prove(ctx, ctx.mkNot(ctx.mkEq(apple, orange)), false); /* Apples pass the apple test */ prove(ctx, ctx.mkApp(fruit.getTesterDecls()[0], apple), false); /* Oranges fail the apple test */ disprove(ctx, ctx.mkApp(fruit.getTesterDecls()[0], orange), false); prove(ctx, ctx.mkNot(ctx.mkApp(fruit.getTesterDecls()[0], orange)), false); Expr<EnumSort<Object>> fruity = ctx.mkConst("fruity", fruit); /* If something is fruity, then it is an apple, banana, or orange */ prove(ctx, ctx.mkOr(ctx.mkEq(fruity, apple), ctx.mkEq(fruity, banana), ctx.mkEq(fruity, orange)), false); } // / Create a list datatype. @SuppressWarnings("unchecked") public void listExample(Context ctx) throws TestFailedException { System.out.println("ListExample"); Log.append("ListExample"); IntSort int_ty = ctx.mkIntSort(); ListSort<IntSort> int_list = ctx.mkListSort(ctx.mkSymbol("int_list"), int_ty); Expr<ListSort<IntSort>> nil = ctx.mkConst(int_list.getNilDecl()); Expr<ListSort<IntSort>> l1 = ctx.mkApp(int_list.getConsDecl(), ctx.mkInt(1), nil); Expr<ListSort<IntSort>> l2 = ctx.mkApp(int_list.getConsDecl(), ctx.mkInt(2), nil); /* nil != cons(1, nil) */ prove(ctx, ctx.mkNot(ctx.mkEq(nil, l1)), false); /* cons(2,nil) != cons(1, nil) */ prove(ctx, ctx.mkNot(ctx.mkEq(l1, l2)), false); /* cons(x,nil) = cons(y, nil) => x = y */ Expr<IntSort> x = ctx.mkConst("x", int_ty); Expr<IntSort> y = ctx.mkConst("y", int_ty); l1 = ctx.mkApp(int_list.getConsDecl(), x, nil); l2 = ctx.mkApp(int_list.getConsDecl(), y, nil); prove(ctx, ctx.mkImplies(ctx.mkEq(l1, l2), ctx.mkEq(x, y)), false); /* cons(x,u) = cons(x, v) => u = v */ Expr<ListSort<IntSort>> u = ctx.mkConst("u", int_list); Expr<ListSort<IntSort>> v = ctx.mkConst("v", int_list); l1 = ctx.mkApp(int_list.getConsDecl(), x, u); l2 = ctx.mkApp(int_list.getConsDecl(), y, v); prove(ctx, ctx.mkImplies(ctx.mkEq(l1, l2), ctx.mkEq(u, v)), false); prove(ctx, ctx.mkImplies(ctx.mkEq(l1, l2), ctx.mkEq(x, y)), false); /* is_nil(u) or is_cons(u) */ prove(ctx, ctx.mkOr(ctx.mkApp(int_list.getIsNilDecl(), u), ctx.mkApp(int_list.getIsConsDecl(), u)), false); /* occurs check u != cons(x,u) */ prove(ctx, ctx.mkNot(ctx.mkEq(u, l1)), false); /* destructors: is_cons(u) => u = cons(head(u),tail(u)) */ BoolExpr fml1 = ctx.mkEq(u, ctx.mkApp(int_list.getConsDecl(), ctx.mkApp(int_list.getHeadDecl(), u), ctx.mkApp(int_list.getTailDecl(), u))); BoolExpr fml = ctx.mkImplies(ctx.mkApp(int_list.getIsConsDecl(), u), fml1); System.out.printf("Formula %s%n", fml); prove(ctx, fml, false); disprove(ctx, fml1, false); } // / Create a binary tree datatype. @SuppressWarnings("unchecked") public <Tree> void treeExample(Context ctx) throws TestFailedException { System.out.println("TreeExample"); Log.append("TreeExample"); String[] head_tail = new String[] { "car", "cdr" }; Sort[] sorts = new Sort[] { null, null }; int[] sort_refs = new int[] { 0, 0 }; Constructor<Tree> nil_con, cons_con; nil_con = ctx.mkConstructor("nil", "is_nil", null, null, null); cons_con = ctx.mkConstructor("cons", "is_cons", head_tail, sorts, sort_refs); Constructor<Tree>[] constructors = new Constructor[] { nil_con, cons_con }; DatatypeSort<Tree> cell = ctx.mkDatatypeSort("cell", constructors); FuncDecl<DatatypeSort<Tree>> nil_decl = nil_con.ConstructorDecl(); FuncDecl<BoolSort> is_nil_decl = nil_con.getTesterDecl(); FuncDecl<DatatypeSort<Tree>> cons_decl = cons_con.ConstructorDecl(); FuncDecl<BoolSort> is_cons_decl = cons_con.getTesterDecl(); FuncDecl<?>[] cons_accessors = cons_con.getAccessorDecls(); FuncDecl<?> car_decl = cons_accessors[0]; FuncDecl<?> cdr_decl = cons_accessors[1]; Expr<DatatypeSort<Tree>> nil = ctx.mkConst(nil_decl); Expr<DatatypeSort<Tree>> l1 = ctx.mkApp(cons_decl, nil, nil); Expr<DatatypeSort<Tree>> l2 = ctx.mkApp(cons_decl, l1, nil); /* nil != cons(nil, nil) */ prove(ctx, ctx.mkNot(ctx.mkEq(nil, l1)), false); /* cons(x,u) = cons(x, v) => u = v */ Expr<DatatypeSort<Tree>> u = ctx.mkConst("u", cell); Expr<DatatypeSort<Tree>> v = ctx.mkConst("v", cell); Expr<DatatypeSort<Tree>> x = ctx.mkConst("x", cell); Expr<DatatypeSort<Tree>> y = ctx.mkConst("y", cell); l1 = ctx.mkApp(cons_decl, x, u); l2 = ctx.mkApp(cons_decl, y, v); prove(ctx, ctx.mkImplies(ctx.mkEq(l1, l2), ctx.mkEq(u, v)), false); prove(ctx, ctx.mkImplies(ctx.mkEq(l1, l2), ctx.mkEq(x, y)), false); /* is_nil(u) or is_cons(u) */ prove(ctx, ctx.mkOr(ctx.mkApp(is_nil_decl, u), ctx.mkApp(is_cons_decl, u)), false); /* occurs check u != cons(x,u) */ prove(ctx, ctx.mkNot(ctx.mkEq(u, l1)), false); /* destructors: is_cons(u) => u = cons(car(u),cdr(u)) */ BoolExpr fml1 = ctx.mkEq(u, ctx.mkApp(cons_decl, ctx.mkApp(car_decl, u), ctx.mkApp(cdr_decl, u))); BoolExpr fml = ctx.mkImplies(ctx.mkApp(is_cons_decl, u), fml1); System.out.printf("Formula %s%n", fml); prove(ctx, fml, false); disprove(ctx, fml1, false); } // / Create a forest of trees. // / <remarks> // / forest ::= nil | cons(tree, forest) // / tree ::= nil | cons(forest, forest) // / </remarks> @SuppressWarnings({"unchecked", "unused", "UnusedAssignment"}) public <Tree, Forest> void forestExample(Context ctx) throws TestFailedException { System.out.println("ForestExample"); Log.append("ForestExample"); DatatypeSort<Forest> forest; DatatypeSort<Tree> tree; FuncDecl<DatatypeSort<Forest>> nil1_decl, cons1_decl, cdr1_decl, car2_decl, cdr2_decl; FuncDecl<DatatypeSort<Tree>> car1_decl, nil2_decl, cons2_decl; FuncDecl<BoolSort> is_nil1_decl, is_nil2_decl, is_cons1_decl, is_cons2_decl; // // Declare the names of the accessors for cons. // Then declare the sorts of the accessors. // For this example, all sorts refer to the new types 'forest' and // 'tree' // being declared, so we pass in null for both sorts1 and sorts2. // On the other hand, the sort_refs arrays contain the indices of the // two new sorts being declared. The first element in sort1_refs // points to 'tree', which has index 1, the second element in sort1_refs // array points to 'forest', which has index 0. // Symbol[] head_tail1 = new Symbol[] { ctx.mkSymbol("head"), ctx.mkSymbol("tail") }; Sort[] sorts1 = new Sort[] { null, null }; int[] sort1_refs = new int[] { 1, 0 }; // the first item points to a // tree, the second to a forest Symbol[] head_tail2 = new Symbol[] { ctx.mkSymbol("car"), ctx.mkSymbol("cdr") }; Sort[] sorts2 = new Sort[] { null, null }; int[] sort2_refs = new int[] { 0, 0 }; // both items point to the forest // datatype. Constructor<Forest> nil1_con, cons1_con; Constructor<Tree> nil2_con, cons2_con; Constructor<Forest>[] constructors1 = new Constructor[2]; Constructor<Tree>[] constructors2 = new Constructor[2]; Symbol[] sort_names = { ctx.mkSymbol("forest"), ctx.mkSymbol("tree") }; /* build a forest */ nil1_con = ctx.mkConstructor(ctx.mkSymbol("nil1"), ctx.mkSymbol("is_nil1"), null, null, null); cons1_con = ctx.mkConstructor(ctx.mkSymbol("cons1"), ctx.mkSymbol("is_cons1"), head_tail1, sorts1, sort1_refs); constructors1[0] = nil1_con; constructors1[1] = cons1_con; /* build a tree */ nil2_con = ctx.mkConstructor(ctx.mkSymbol("nil2"), ctx.mkSymbol("is_nil2"), null, null, null); cons2_con = ctx.mkConstructor(ctx.mkSymbol("cons2"), ctx.mkSymbol("is_cons2"), head_tail2, sorts2, sort2_refs); constructors2[0] = nil2_con; constructors2[1] = cons2_con; Constructor<Object>[][] clists = new Constructor[][] { constructors1, constructors2 }; Sort[] sorts = ctx.mkDatatypeSorts(sort_names, clists); forest = (DatatypeSort<Forest>) sorts[0]; tree = (DatatypeSort<Tree>) sorts[1]; // // Now that the datatype has been created. // Query the constructors for the constructor // functions, testers, and field accessors. // nil1_decl = nil1_con.ConstructorDecl(); is_nil1_decl = nil1_con.getTesterDecl(); cons1_decl = cons1_con.ConstructorDecl(); is_cons1_decl = cons1_con.getTesterDecl(); FuncDecl<?>[] cons1_accessors = cons1_con.getAccessorDecls(); car1_decl = (FuncDecl<DatatypeSort<Tree>>) cons1_accessors[0]; cdr1_decl = (FuncDecl<DatatypeSort<Forest>>) cons1_accessors[1]; nil2_decl = nil2_con.ConstructorDecl(); is_nil2_decl = nil2_con.getTesterDecl(); cons2_decl = cons2_con.ConstructorDecl(); is_cons2_decl = cons2_con.getTesterDecl(); FuncDecl<?>[] cons2_accessors = cons2_con.getAccessorDecls(); car2_decl = (FuncDecl<DatatypeSort<Forest>>) cons2_accessors[0]; cdr2_decl = (FuncDecl<DatatypeSort<Forest>>) cons2_accessors[1]; Expr<DatatypeSort<Forest>> nil1 = ctx.mkConst(nil1_decl); Expr<DatatypeSort<Tree>> nil2 = ctx.mkConst(nil2_decl); Expr<DatatypeSort<Forest>> f1 = ctx.mkApp(cons1_decl, nil2, nil1); Expr<DatatypeSort<Tree>> t1 = ctx.mkApp(cons2_decl, nil1, nil1); Expr<DatatypeSort<Tree>> t2 = ctx.mkApp(cons2_decl, f1, nil1); Expr<DatatypeSort<Tree>> t3 = ctx.mkApp(cons2_decl, f1, f1); Expr<DatatypeSort<Tree>> t4 = ctx.mkApp(cons2_decl, nil1, f1); Expr<DatatypeSort<Forest>> f2 = ctx.mkApp(cons1_decl, t1, nil1); Expr<DatatypeSort<Forest>> f3 = ctx.mkApp(cons1_decl, t1, f1); /* nil != cons(nil,nil) */ prove(ctx, ctx.mkNot(ctx.mkEq(nil1, f1)), false); prove(ctx, ctx.mkNot(ctx.mkEq(nil2, t1)), false); /* cons(x,u) = cons(x, v) => u = v */ Expr<DatatypeSort<Forest>> u = ctx.mkConst("u", forest); Expr<DatatypeSort<Forest>> v = ctx.mkConst("v", forest); Expr<DatatypeSort<Tree>> x = ctx.mkConst("x", tree); Expr<DatatypeSort<Tree>> y = ctx.mkConst("y", tree); Expr<DatatypeSort<Forest>> l1 = ctx.mkApp(cons1_decl, x, u); Expr<DatatypeSort<Forest>> l2 = ctx.mkApp(cons1_decl, y, v); prove(ctx, ctx.mkImplies(ctx.mkEq(l1, l2), ctx.mkEq(u, v)), false); prove(ctx, ctx.mkImplies(ctx.mkEq(l1, l2), ctx.mkEq(x, y)), false); /* is_nil(u) or is_cons(u) */ prove(ctx, ctx.mkOr(ctx.mkApp(is_nil1_decl, u), ctx.mkApp(is_cons1_decl, u)), false); /* occurs check u != cons(x,u) */ prove(ctx, ctx.mkNot(ctx.mkEq(u, l1)), false); } // / Demonstrate how to use #Eval. public void evalExample1(Context ctx) { System.out.println("EvalExample1"); Log.append("EvalExample1"); IntExpr x = ctx.mkIntConst("x"); IntExpr y = ctx.mkIntConst("y"); IntNum two = ctx.mkInt(2); Solver solver = ctx.mkSolver(); /* assert x < y */ solver.add(ctx.mkLt(x, y)); /* assert x > 2 */ solver.add(ctx.mkGt(x, two)); /* find model for the constraints above */ Model model = null; if (Status.SATISFIABLE == solver.check()) { model = solver.getModel(); System.out.println(model); System.out.println("\nevaluating x+y"); Expr<IntSort> v = model.evaluate(ctx.mkAdd(x, y), false); if (v != null) { System.out.printf("result = %s%n", v); } else { System.out.println("Failed to evaluate: x+y"); } } else { System.out.println("BUG, the constraints are satisfiable."); } } // / Demonstrate how to use #Eval on tuples. @SuppressWarnings("unchecked") public void evalExample2(Context ctx) { System.out.println("EvalExample2"); Log.append("EvalExample2"); IntSort int_type = ctx.getIntSort(); TupleSort tuple = ctx.mkTupleSort(ctx.mkSymbol("mk_tuple"), // name of // tuple // constructor new Symbol[] { ctx.mkSymbol("first"), ctx.mkSymbol("second") }, // names // of // projection // operators new Sort[] { int_type, int_type } // types of projection // operators ); FuncDecl<IntSort> first = (FuncDecl<IntSort>) tuple.getFieldDecls()[0]; // declarations are for // projections FuncDecl<IntSort> second = (FuncDecl<IntSort>) tuple.getFieldDecls()[1]; Expr<TupleSort> tup1 = ctx.mkConst("t1", tuple); Expr<TupleSort> tup2 = ctx.mkConst("t2", tuple); Solver solver = ctx.mkSolver(); /* assert tup1 != tup2 */ solver.add(ctx.mkNot(ctx.mkEq(tup1, tup2))); /* assert first tup1 = first tup2 */ solver.add(ctx.mkEq(ctx.mkApp(first, tup1), ctx.mkApp(first, tup2))); /* find model for the constraints above */ Model model = null; if (Status.SATISFIABLE == solver.check()) { model = solver.getModel(); System.out.println(model); System.out.printf("evaluating tup1 %s%n", model.evaluate(tup1, false)); System.out.printf("evaluating tup2 %s%n", model.evaluate(tup2, false)); System.out.printf("evaluating second(tup2) %s%n", model.evaluate(ctx.mkApp(second, tup2), false)); } else { System.out.println("BUG, the constraints are satisfiable."); } } // / Demonstrate how to use <code>Push</code>and <code>Pop</code>to // / control the size of models. // / <remarks>Note: this test is specialized to 32-bit bitvectors.</remarks> public void checkSmall(Context ctx, Solver solver, BitVecExpr... to_minimize) { int num_Exprs = to_minimize.length; int[] upper = new int[num_Exprs]; int[] lower = new int[num_Exprs]; for (int i = 0; i < upper.length; ++i) { upper[i] = Integer.MAX_VALUE; lower[i] = 0; } boolean some_work = true; int last_index = -1; int last_upper = 0; while (some_work) { solver.push(); boolean check_is_sat = true; while (some_work) { // Assert all feasible bounds. for (int i = 0; i < num_Exprs; ++i) { solver.add(ctx.mkBVULE(to_minimize[i], ctx.mkBV(upper[i], 32))); } check_is_sat = Status.SATISFIABLE == solver.check(); if (!check_is_sat) { if (last_index != -1) { lower[last_index] = last_upper + 1; } break; } System.out.println(solver.getModel()); // narrow the bounds based on the current model. for (int i = 0; i < num_Exprs; ++i) { Expr<BitVecSort> v = solver.getModel().evaluate(to_minimize[i], false); // we still have to cast because we want to use a method in BitVecNum // however, we cannot cast to a type which doesn't match the generic, e.g. IntNum int ui = ((BitVecNum) v).getInt(); if (ui < upper[i]) { upper[i] = ui; } System.out.printf("%d %d %d%n", i, lower[i], upper[i]); } // find a new bound to add some_work = false; last_index = 0; for (int i = 0; i < num_Exprs; ++i) { if (lower[i] < upper[i]) { last_upper = (upper[i] + lower[i]) / 2; last_index = i; solver.add(ctx.mkBVULE(to_minimize[i], ctx.mkBV(last_upper, 32))); some_work = true; break; } } } solver.pop(); } } // / Reduced-size model generation example. public void findSmallModelExample(Context ctx) { System.out.println("FindSmallModelExample"); Log.append("FindSmallModelExample"); BitVecExpr x = ctx.mkBVConst("x", 32); BitVecExpr y = ctx.mkBVConst("y", 32); BitVecExpr z = ctx.mkBVConst("z", 32); Solver solver = ctx.mkSolver(); solver.add(ctx.mkBVULE(x, ctx.mkBVAdd(y, z))); checkSmall(ctx, solver, x, y, z); } // / Simplifier example. @SuppressWarnings("unchecked") public void simplifierExample(Context ctx) { System.out.println("SimplifierExample"); Log.append("SimplifierExample"); IntExpr x = ctx.mkIntConst("x"); IntExpr y = ctx.mkIntConst("y"); IntExpr z = ctx.mkIntConst("z"); @SuppressWarnings("unused") IntExpr u = ctx.mkIntConst("u"); ArithExpr<IntSort> t1 = ctx.mkAdd(x, ctx.mkSub(y, ctx.mkAdd(x, z))); Expr<IntSort> t2 = t1.simplify(); System.out.printf("%s -> %s%n", t1, t2); } // / Extract unsatisfiable core example public void unsatCoreAndProofExample(Context ctx) { System.out.println("UnsatCoreAndProofExample"); Log.append("UnsatCoreAndProofExample"); Solver solver = ctx.mkSolver(); BoolExpr pa = ctx.mkBoolConst("PredA"); BoolExpr pb = ctx.mkBoolConst("PredB"); BoolExpr pc = ctx.mkBoolConst("PredC"); BoolExpr pd = ctx.mkBoolConst("PredD"); BoolExpr p1 = ctx.mkBoolConst("P1"); BoolExpr p2 = ctx.mkBoolConst("P2"); BoolExpr p3 = ctx.mkBoolConst("P3"); BoolExpr p4 = ctx.mkBoolConst("P4"); BoolExpr[] assumptions = new BoolExpr[] { ctx.mkNot(p1), ctx.mkNot(p2), ctx.mkNot(p3), ctx.mkNot(p4) }; BoolExpr f1 = ctx.mkAnd(pa, pb, pc); BoolExpr f2 = ctx.mkAnd(pa, ctx.mkNot(pb), pc); BoolExpr f3 = ctx.mkOr(ctx.mkNot(pa), ctx.mkNot(pc)); BoolExpr f4 = pd; solver.add(ctx.mkOr(f1, p1)); solver.add(ctx.mkOr(f2, p2)); solver.add(ctx.mkOr(f3, p3)); solver.add(ctx.mkOr(f4, p4)); Status result = solver.check(assumptions); if (result == Status.UNSATISFIABLE) { System.out.println("unsat"); System.out.printf("proof: %s%n", solver.getProof()); System.out.println("core: "); for (Expr<?> c : solver.getUnsatCore()) { System.out.println(c); } } } /// Extract unsatisfiable core example with AssertAndTrack public void unsatCoreAndProofExample2(Context ctx) { System.out.println("UnsatCoreAndProofExample2"); Log.append("UnsatCoreAndProofExample2"); Solver solver = ctx.mkSolver(); BoolExpr pa = ctx.mkBoolConst("PredA"); BoolExpr pb = ctx.mkBoolConst("PredB"); BoolExpr pc = ctx.mkBoolConst("PredC"); BoolExpr pd = ctx.mkBoolConst("PredD"); BoolExpr f1 = ctx.mkAnd(new BoolExpr[] { pa, pb, pc }); BoolExpr f2 = ctx.mkAnd(new BoolExpr[] { pa, ctx.mkNot(pb), pc }); BoolExpr f3 = ctx.mkOr(ctx.mkNot(pa), ctx.mkNot(pc)); BoolExpr f4 = pd; BoolExpr p1 = ctx.mkBoolConst("P1"); BoolExpr p2 = ctx.mkBoolConst("P2"); BoolExpr p3 = ctx.mkBoolConst("P3"); BoolExpr p4 = ctx.mkBoolConst("P4"); solver.assertAndTrack(f1, p1); solver.assertAndTrack(f2, p2); solver.assertAndTrack(f3, p3); solver.assertAndTrack(f4, p4); Status result = solver.check(); if (result == Status.UNSATISFIABLE) { System.out.println("unsat"); System.out.println("core: "); for (Expr<?> c : solver.getUnsatCore()) { System.out.println(c); } } } public <S, T> void finiteDomainExample(Context ctx) { System.out.println("FiniteDomainExample"); Log.append("FiniteDomainExample"); FiniteDomainSort<S> s = ctx.mkFiniteDomainSort("S", 10); FiniteDomainSort<T> t = ctx.mkFiniteDomainSort("T", 10); FiniteDomainNum<S> s1 = (FiniteDomainNum<S>) ctx.mkNumeral(1, s); FiniteDomainNum<T> t1 = (FiniteDomainNum<T>) ctx.mkNumeral(1, t); System.out.println(s); System.out.println(t); System.out.println(s1); System.out.println(t1); System.out.println(s1.getInt()); System.out.println(t1.getInt()); // But you cannot mix numerals of different sorts // even if the size of their domains are the same: // System.out.println(ctx.mkEq(s1, t1)); } public void floatingPointExample1(Context ctx) throws TestFailedException { System.out.println("FloatingPointExample1"); Log.append("FloatingPointExample1"); FPSort s = ctx.mkFPSort(11, 53); System.out.printf("Sort: %s%n", s); FPNum x = (FPNum)ctx.mkNumeral("-1e1", s); /* -1 * 10^1 = -10 */ FPNum y = (FPNum)ctx.mkNumeral("-10", s); /* -10 */ FPNum z = (FPNum)ctx.mkNumeral("-1.25p3", s); /* -1.25 * 2^3 = -1.25 * 8 = -10 */ System.out.printf("x=%s; y=%s; z=%s%n", x.toString(), y.toString(), z.toString()); BoolExpr a = ctx.mkAnd(ctx.mkFPEq(x, y), ctx.mkFPEq(y, z)); check(ctx, ctx.mkNot(a), Status.UNSATISFIABLE); /* nothing is equal to NaN according to floating-point * equality, so NaN == k should be unsatisfiable. */ FPExpr k = (FPExpr)ctx.mkConst("x", s); FPExpr nan = ctx.mkFPNaN(s); /* solver that runs the default tactic for QF_FP. */ Solver slvr = ctx.mkSolver("QF_FP"); slvr.add(ctx.mkFPEq(nan, k)); if (slvr.check() != Status.UNSATISFIABLE) throw new TestFailedException(); System.out.printf("OK, unsat:%n%s%n", slvr); /* NaN is equal to NaN according to normal equality. */ slvr = ctx.mkSolver("QF_FP"); slvr.add(ctx.mkEq(nan, nan)); if (slvr.check() != Status.SATISFIABLE) throw new TestFailedException(); System.out.printf("OK, sat:%n%s%n", slvr); /* Let's prove -1e1 * -1.25e3 == +100 */ x = (FPNum)ctx.mkNumeral("-1e1", s); y = (FPNum)ctx.mkNumeral("-1.25p3", s); FPExpr x_plus_y = (FPExpr)ctx.mkConst("x_plus_y", s); FPNum r = (FPNum)ctx.mkNumeral("100", s); slvr = ctx.mkSolver("QF_FP"); slvr.add(ctx.mkEq(x_plus_y, ctx.mkFPMul(ctx.mkFPRoundNearestTiesToAway(), x, y))); slvr.add(ctx.mkNot(ctx.mkFPEq(x_plus_y, r))); if (slvr.check() != Status.UNSATISFIABLE) throw new TestFailedException(); System.out.printf("OK, unsat:%n%s%n", slvr); } public void floatingPointExample2(Context ctx) throws TestFailedException { System.out.println("FloatingPointExample2"); Log.append("FloatingPointExample2"); FPSort double_sort = ctx.mkFPSort(11, 53); FPRMSort rm_sort = ctx.mkFPRoundingModeSort(); FPRMExpr rm = (FPRMExpr)ctx.mkConst(ctx.mkSymbol("rm"), rm_sort); BitVecExpr x = (BitVecExpr)ctx.mkConst(ctx.mkSymbol("x"), ctx.mkBitVecSort(64)); FPExpr y = (FPExpr)ctx.mkConst(ctx.mkSymbol("y"), double_sort); FPExpr fp_val = ctx.mkFP(42, double_sort); BoolExpr c1 = ctx.mkEq(y, fp_val); BoolExpr c2 = ctx.mkEq(x, ctx.mkFPToBV(rm, y, 64, false)); BoolExpr c3 = ctx.mkEq(x, ctx.mkBV(42, 64)); BoolExpr c4 = ctx.mkEq(ctx.mkNumeral(42, ctx.getRealSort()), ctx.mkFPToReal(fp_val)); BoolExpr c5 = ctx.mkAnd(c1, c2, c3, c4); System.out.printf("c5 = %s%n", c5); /* Generic solver */ Solver s = ctx.mkSolver(); s.add(c5); if (s.check() != Status.SATISFIABLE) throw new TestFailedException(); System.out.printf("OK, model: %s%n", s.getModel()); } @SuppressWarnings("unchecked") public void optimizeExample(Context ctx) { System.out.println("Opt"); Optimize opt = ctx.mkOptimize(); // Set constraints. IntExpr xExp = ctx.mkIntConst("x"); IntExpr yExp = ctx.mkIntConst("y"); opt.Add(ctx.mkEq(ctx.mkAdd(xExp, yExp), ctx.mkInt(10)), ctx.mkGe(xExp, ctx.mkInt(0)), ctx.mkGe(yExp, ctx.mkInt(0))); // Set objectives. Optimize.Handle<IntSort> mx = opt.MkMaximize(xExp); Optimize.Handle<IntSort> my = opt.MkMaximize(yExp); System.out.println(opt.Check()); System.out.println(mx); System.out.println(my); } public void translationExample() { Context ctx1 = new Context(); Context ctx2 = new Context(); Sort s1 = ctx1.getIntSort(); Sort s2 = ctx2.getIntSort(); Sort s3 = s1.translate(ctx2); System.out.println(s1 == s2); System.out.println(s1.equals(s2)); System.out.println(s2.equals(s3)); System.out.println(s1.equals(s3)); IntExpr e1 = ctx1.mkIntConst("e1"); IntExpr e2 = ctx2.mkIntConst("e1"); Expr<IntSort> e3 = e1.translate(ctx2); System.out.println(e1 == e2); System.out.println(e1.equals(e2)); System.out.println(e2.equals(e3)); System.out.println(e1.equals(e3)); } public static void main(String[] args) { JavaGenericExample p = new JavaGenericExample(); try { Global.ToggleWarningMessages(true); Log.open("test.log"); System.out.print("Z3 Major Version: "); System.out.println(Version.getMajor()); System.out.print("Z3 Full Version: "); System.out.println(Version.getString()); System.out.print("Z3 Full Version String: "); System.out.println(Version.getFullVersion()); p.simpleExample(); { // These examples need model generation turned on. HashMap<String, String> cfg = new HashMap<>(); cfg.put("model", "true"); Context ctx = new Context(cfg); p.optimizeExample(ctx); p.basicTests(ctx); p.sudokuExample(ctx); p.quantifierExample1(ctx); p.quantifierExample2(ctx); p.logicExample(ctx); p.parOrExample(ctx); p.findModelExample1(ctx); p.findModelExample2(ctx); p.pushPopExample1(ctx); p.arrayExample1(ctx); p.arrayExample3(ctx); p.bitvectorExample1(ctx); p.bitvectorExample2(ctx); p.parserExample1(ctx); p.parserExample2(ctx); p.parserExample5(ctx); p.iteExample(ctx); p.evalExample1(ctx); p.evalExample2(ctx); p.findSmallModelExample(ctx); p.simplifierExample(ctx); p.finiteDomainExample(ctx); p.floatingPointExample1(ctx); // core dumps: p.floatingPointExample2(ctx); } { // These examples need proof generation turned on. HashMap<String, String> cfg = new HashMap<>(); cfg.put("proof", "true"); Context ctx = new Context(cfg); p.proveExample1(ctx); p.proveExample2(ctx); p.arrayExample2(ctx); p.tupleExample(ctx); // throws p.parserExample3(ctx); p.enumExampleTyped(ctx); p.enumExampleUntyped(ctx); p.listExample(ctx); p.treeExample(ctx); p.forestExample(ctx); p.unsatCoreAndProofExample(ctx); p.unsatCoreAndProofExample2(ctx); } { // These examples need proof generation turned on and auto-config // set to false. HashMap<String, String> cfg = new HashMap<>(); cfg.put("proof", "true"); cfg.put("auto-config", "false"); Context ctx = new Context(cfg); p.quantifierExample3(ctx); p.quantifierExample4(ctx); } p.translationExample(); Log.close(); if (Log.isOpen()) System.out.println("Log is still open!"); } catch (Z3Exception ex) { System.out.printf("Z3 Managed Exception: %s%n", ex.getMessage()); System.out.println("Stack trace: "); ex.printStackTrace(System.out); } catch (TestFailedException ex) { System.out.printf("TEST CASE FAILED: %s%n", ex.getMessage()); System.out.println("Stack trace: "); ex.printStackTrace(System.out); } catch (Exception ex) { System.out.printf("Unknown Exception: %s%n", ex.getMessage()); System.out.println("Stack trace: "); ex.printStackTrace(System.out); } } }
81,822
36.758653
229
java
z3
z3-master/src/api/java/AST.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: AST.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import com.microsoft.z3.enumerations.Z3_ast_kind; /** * The abstract syntax tree (AST) class. **/ public class AST extends Z3Object implements Comparable<AST> { /** * Object comparison. * * @param o another AST **/ @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof AST)) return false; AST casted = (AST) o; return (getContext().nCtx() == casted.getContext().nCtx()) && (Native.isEqAst(getContext().nCtx(), getNativeObject(), casted.getNativeObject())); } /** * Object Comparison. * @param other Another AST * * @return Negative if the object should be sorted before {@code other}, * positive if after else zero. * @throws Z3Exception on error **/ @Override public int compareTo(AST other) { if (other == null) { return 1; } return Integer.compare(getId(), other.getId()); } /** * The AST's hash code. * * @return A hash code **/ @Override public int hashCode() { return Native.getAstHash(getContext().nCtx(), getNativeObject()); } /** * A unique identifier for the AST (unique among all ASTs). * @throws Z3Exception on error **/ public int getId() { return Native.getAstId(getContext().nCtx(), getNativeObject()); } /** * Translates (copies) the AST to the Context {@code ctx}. * @param ctx A context * * @return A copy of the AST which is associated with {@code ctx} * @throws Z3Exception on error **/ public AST translate(Context ctx) { if (getContext() == ctx) { return this; } else { return create(ctx, Native.translate(getContext().nCtx(), getNativeObject(), ctx.nCtx())); } } /** * The kind of the AST. * @throws Z3Exception on error **/ public Z3_ast_kind getASTKind() { return Z3_ast_kind.fromInt(Native.getAstKind(getContext().nCtx(), getNativeObject())); } /** * Indicates whether the AST is an Expr * @throws Z3Exception on error * @throws Z3Exception on error **/ public boolean isExpr() { switch (getASTKind()) { case Z3_APP_AST: case Z3_NUMERAL_AST: case Z3_QUANTIFIER_AST: case Z3_VAR_AST: return true; default: return false; } } /** * Indicates whether the AST is an application * @return a boolean * @throws Z3Exception on error **/ public boolean isApp() { return this.getASTKind() == Z3_ast_kind.Z3_APP_AST; } /** * Indicates whether the AST is a BoundVariable. * @return a boolean * @throws Z3Exception on error **/ public boolean isVar() { return this.getASTKind() == Z3_ast_kind.Z3_VAR_AST; } /** * Indicates whether the AST is a Quantifier * @return a boolean * @throws Z3Exception on error **/ public boolean isQuantifier() { return this.getASTKind() == Z3_ast_kind.Z3_QUANTIFIER_AST; } /** * Indicates whether the AST is a Sort **/ public boolean isSort() { return this.getASTKind() == Z3_ast_kind.Z3_SORT_AST; } /** * Indicates whether the AST is a FunctionDeclaration **/ public boolean isFuncDecl() { return this.getASTKind() == Z3_ast_kind.Z3_FUNC_DECL_AST; } /** * A string representation of the AST. **/ @Override public String toString() { return Native.astToString(getContext().nCtx(), getNativeObject()); } /** * A string representation of the AST in s-expression notation. **/ public String getSExpr() { return Native.astToString(getContext().nCtx(), getNativeObject()); } AST(Context ctx, long obj) { super(ctx, obj); } @Override void incRef() { Native.incRef(getContext().nCtx(), getNativeObject()); } @Override void addToReferenceQueue() { getContext().getASTDRQ().storeReference(getContext(), this); } static AST create(Context ctx, long obj) { switch (Z3_ast_kind.fromInt(Native.getAstKind(ctx.nCtx(), obj))) { case Z3_FUNC_DECL_AST: return new FuncDecl<>(ctx, obj); case Z3_QUANTIFIER_AST: return new Quantifier(ctx, obj); case Z3_SORT_AST: return Sort.create(ctx, obj); case Z3_APP_AST: case Z3_NUMERAL_AST: case Z3_VAR_AST: return Expr.create(ctx, obj); default: throw new Z3Exception("Unknown AST kind"); } } }
5,055
21.877828
101
java
z3
z3-master/src/api/java/ASTDecRefQueue.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: ASTDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; class ASTDecRefQueue extends IDecRefQueue<AST> { public ASTDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.decRef(ctx.nCtx(), obj); } };
437
12.6875
56
java
z3
z3-master/src/api/java/ASTMap.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: ASTMap.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Map from AST to AST **/ class ASTMap extends Z3Object { /** * Checks whether the map contains the key {@code k}. * @param k An AST * * @return True if {@code k} is a key in the map, false * otherwise. **/ public boolean contains(AST k) { return Native.astMapContains(getContext().nCtx(), getNativeObject(), k.getNativeObject()); } /** * Finds the value associated with the key {@code k}. * Remarks: This function signs an error when {@code k} is not a key in * the map. * @param k An AST * * @throws Z3Exception **/ public AST find(AST k) { return new AST(getContext(), Native.astMapFind(getContext().nCtx(), getNativeObject(), k.getNativeObject())); } /** * Stores or replaces a new key/value pair in the map. * @param k The key AST * @param v The value AST **/ public void insert(AST k, AST v) { Native.astMapInsert(getContext().nCtx(), getNativeObject(), k.getNativeObject(), v.getNativeObject()); } /** * Erases the key {@code k} from the map. * @param k An AST **/ public void erase(AST k) { Native.astMapErase(getContext().nCtx(), getNativeObject(), k.getNativeObject()); } /** * Removes all keys from the map. **/ public void reset() { Native.astMapReset(getContext().nCtx(), getNativeObject()); } /** * The size of the map **/ public int size() { return Native.astMapSize(getContext().nCtx(), getNativeObject()); } /** * The keys stored in the map. * * @throws Z3Exception **/ public AST[] getKeys() { ASTVector av = new ASTVector(getContext(), Native.astMapKeys(getContext().nCtx(), getNativeObject())); return av.ToArray(); } /** * Retrieves a string representation of the map. **/ @Override public String toString() { return Native.astMapToString(getContext().nCtx(), getNativeObject()); } ASTMap(Context ctx, long obj) { super(ctx, obj); } ASTMap(Context ctx) { super(ctx, Native.mkAstMap(ctx.nCtx())); } @Override void incRef() { Native.astMapIncRef(getContext().nCtx(), getNativeObject()); } @Override void addToReferenceQueue() { getContext().getASTMapDRQ().storeReference(getContext(), this); } }
2,739
20.24031
110
java
z3
z3-master/src/api/java/ASTVector.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: ASTVector.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Vectors of ASTs. **/ public class ASTVector extends Z3Object { /** * The size of the vector **/ public int size() { return Native.astVectorSize(getContext().nCtx(), getNativeObject()); } /** * Retrieves the i-th object in the vector. * Remarks: May throw an {@code IndexOutOfBoundsException} when * {@code i} is out of range. * @param i Index * * @return An AST * @throws Z3Exception **/ public AST get(int i) { return new AST(getContext(), Native.astVectorGet(getContext().nCtx(), getNativeObject(), i)); } public void set(int i, AST value) { Native.astVectorSet(getContext().nCtx(), getNativeObject(), i, value.getNativeObject()); } /** * Resize the vector to {@code newSize}. * @param newSize The new size of the vector. **/ public void resize(int newSize) { Native.astVectorResize(getContext().nCtx(), getNativeObject(), newSize); } /** * Add the AST {@code a} to the back of the vector. The size is * increased by 1. * @param a An AST **/ public void push(AST a) { Native.astVectorPush(getContext().nCtx(), getNativeObject(), a.getNativeObject()); } /** * Translates all ASTs in the vector to {@code ctx}. * @param ctx A context * * @return A new ASTVector * @throws Z3Exception **/ public ASTVector translate(Context ctx) { return new ASTVector(getContext(), Native.astVectorTranslate(getContext() .nCtx(), getNativeObject(), ctx.nCtx())); } /** * Retrieves a string representation of the vector. **/ @Override public String toString() { return Native.astVectorToString(getContext().nCtx(), getNativeObject()); } public ASTVector(Context ctx, long obj) { super(ctx, obj); } public ASTVector(Context ctx) { super(ctx, Native.mkAstVector(ctx.nCtx())); } @Override void incRef() { Native.astVectorIncRef(getContext().nCtx(), getNativeObject()); } @Override void addToReferenceQueue() { getContext().getASTVectorDRQ().storeReference(getContext(), this); } /** * Translates the AST vector into an AST[] * */ public AST[] ToArray() { int n = size(); AST[] res = new AST[n]; for (int i = 0; i < n; i++) res[i] = AST.create(getContext(), get(i).getNativeObject()); return res; } /** * Translates the AST vector into an Expr[] * */ public Expr<?>[] ToExprArray() { int n = size(); Expr<?>[] res = new Expr[n]; for (int i = 0; i < n; i++) res[i] = Expr.create(getContext(), get(i).getNativeObject()); return res; } /** * Translates the AST vector into an BoolExpr[] * */ public BoolExpr[] ToBoolExprArray() { int n = size(); BoolExpr[] res = new BoolExpr[n]; for (int i = 0; i < n; i++) res[i] = (BoolExpr) Expr.create(getContext(), get(i).getNativeObject()); return res; } /** * Translates the AST vector into an BitVecExpr[] * */ public BitVecExpr[] ToBitVecExprArray() { int n = size(); BitVecExpr[] res = new BitVecExpr[n]; for (int i = 0; i < n; i++) res[i] = (BitVecExpr)Expr.create(getContext(), get(i).getNativeObject()); return res; } /** * Translates the AST vector into an ArithExpr[] * */ public ArithExpr<?>[] ToArithExprExprArray() { int n = size(); ArithExpr<?>[] res = new ArithExpr[n]; for (int i = 0; i < n; i++) res[i] = (ArithExpr<?>)Expr.create(getContext(), get(i).getNativeObject()); return res; } /** * Translates the AST vector into an ArrayExpr[] * */ public ArrayExpr<?, ?>[] ToArrayExprArray() { int n = size(); ArrayExpr<?, ?>[] res = new ArrayExpr[n]; for (int i = 0; i < n; i++) res[i] = (ArrayExpr<?, ?>)Expr.create(getContext(), get(i).getNativeObject()); return res; } /** * Translates the AST vector into an DatatypeExpr[] * */ public DatatypeExpr<?>[] ToDatatypeExprArray() { int n = size(); DatatypeExpr<?>[] res = new DatatypeExpr[n]; for (int i = 0; i < n; i++) res[i] = (DatatypeExpr<?>)Expr.create(getContext(), get(i).getNativeObject()); return res; } /** * Translates the AST vector into an FPExpr[] * */ public FPExpr[] ToFPExprArray() { int n = size(); FPExpr[] res = new FPExpr[n]; for (int i = 0; i < n; i++) res[i] = (FPExpr)Expr.create(getContext(), get(i).getNativeObject()); return res; } /** * Translates the AST vector into an FPRMExpr[] * */ public FPRMExpr[] ToFPRMExprArray() { int n = size(); FPRMExpr[] res = new FPRMExpr[n]; for (int i = 0; i < n; i++) res[i] = (FPRMExpr)Expr.create(getContext(), get(i).getNativeObject()); return res; } /** * Translates the AST vector into an IntExpr[] * */ public IntExpr[] ToIntExprArray() { int n = size(); IntExpr[] res = new IntExpr[n]; for (int i = 0; i < n; i++) res[i] = (IntExpr)Expr.create(getContext(), get(i).getNativeObject()); return res; } /** * Translates the AST vector into an RealExpr[] * */ public RealExpr[] ToRealExprArray() { int n = size(); RealExpr[] res = new RealExpr[n]; for (int i = 0; i < n; i++) res[i] = (RealExpr)Expr.create(getContext(), get(i).getNativeObject()); return res; } }
6,162
24.258197
90
java
z3
z3-master/src/api/java/AlgebraicNum.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: AlgebraicNum.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Algebraic numbers **/ public class AlgebraicNum extends ArithExpr { /** * Return a upper bound for a given real algebraic number. The interval * isolating the number is smaller than 1/10^{@code precision}. * * @see Expr#isAlgebraicNumber * @param precision the precision of the result * * @return A numeral Expr of sort Real * @throws Z3Exception on error **/ public RatNum toUpper(int precision) { return new RatNum(getContext(), Native.getAlgebraicNumberUpper(getContext() .nCtx(), getNativeObject(), precision)); } /** * Return a lower bound for the given real algebraic number. The interval * isolating the number is smaller than 1/10^{@code precision}. * * @see Expr#isAlgebraicNumber * @param precision precision * * @return A numeral Expr of sort Real * @throws Z3Exception on error **/ public RatNum toLower(int precision) { return new RatNum(getContext(), Native.getAlgebraicNumberLower(getContext() .nCtx(), getNativeObject(), precision)); } /** * Returns a string representation in decimal notation. * Remarks: The result has at most {@code precision} decimal places. * @param precision precision * @return String * @throws Z3Exception on error **/ public String toDecimal(int precision) { return Native.getNumeralDecimalString(getContext().nCtx(), getNativeObject(), precision); } AlgebraicNum(Context ctx, long obj) { super(ctx, obj); } }
1,844
22.35443
85
java
z3
z3-master/src/api/java/ApplyResult.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: ApplyResult.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * ApplyResult objects represent the result of an application of a tactic to a * goal. It contains the subgoals that were produced. **/ public class ApplyResult extends Z3Object { /** * The number of Subgoals. **/ public int getNumSubgoals() { return Native.applyResultGetNumSubgoals(getContext().nCtx(), getNativeObject()); } /** * Retrieves the subgoals from the ApplyResult. * * @throws Z3Exception **/ public Goal[] getSubgoals() { int n = getNumSubgoals(); Goal[] res = new Goal[n]; for (int i = 0; i < n; i++) res[i] = new Goal(getContext(), Native.applyResultGetSubgoal(getContext().nCtx(), getNativeObject(), i)); return res; } /** * A string representation of the ApplyResult. **/ @Override public String toString() { return Native.applyResultToString(getContext().nCtx(), getNativeObject()); } ApplyResult(Context ctx, long obj) { super(ctx, obj); } @Override void incRef() { Native.applyResultIncRef(getContext().nCtx(), getNativeObject()); } @Override void addToReferenceQueue() { getContext().getApplyResultDRQ().storeReference(getContext(), this); } }
1,531
20.277778
89
java
z3
z3-master/src/api/java/ApplyResultDecRefQueue.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: ApplyResultDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; class ApplyResultDecRefQueue extends IDecRefQueue<ApplyResult> { public ApplyResultDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.applyResultDecRef(ctx.nCtx(), obj); } };
480
14.03125
62
java
z3
z3-master/src/api/java/ArithExpr.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: ArithExpr.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Arithmetic expressions (int/real) **/ public class ArithExpr<R extends ArithSort> extends Expr<R> { /** * Constructor for ArithExpr **/ ArithExpr(Context ctx, long obj) { super(ctx, obj); } }
444
12.484848
59
java
z3
z3-master/src/api/java/ArithSort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: ArithSort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * An arithmetic sort, i.e., Int or Real. **/ public class ArithSort extends Sort { ArithSort(Context ctx, long obj) { super(ctx, obj); } };
376
11.566667
56
java
z3
z3-master/src/api/java/ArrayExpr.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: ArrayExpr.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Array expressions **/ public class ArrayExpr<D extends Sort, R extends Sort> extends Expr<ArraySort<D, R>> { /** * Constructor for ArrayExpr **/ ArrayExpr(Context ctx, long obj) { super(ctx, obj); } }
454
12.382353
84
java
z3
z3-master/src/api/java/ArraySort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: ArraySort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Array sorts. **/ @SuppressWarnings("unchecked") public class ArraySort<D extends Sort, R extends Sort> extends Sort { /** * The domain of the array sort. * @throws Z3Exception * @throws Z3Exception on error * @return a sort **/ public D getDomain() { return (D) Sort.create(getContext(), Native.getArraySortDomain(getContext().nCtx(), getNativeObject())); } /** * The domain of a multi-dimensional array sort. * @throws Z3Exception * @throws Z3Exception on error * @return a sort **/ public D getDomain(int idx) { return (D) Sort.create(getContext(), Native.getArraySortDomainN(getContext().nCtx(), getNativeObject(), idx)); } /** * The range of the array sort. * @throws Z3Exception * @throws Z3Exception on error * @return a sort **/ public R getRange() { return (R) Sort.create(getContext(), Native.getArraySortRange(getContext().nCtx(), getNativeObject())); } ArraySort(Context ctx, long obj) { super(ctx, obj); } ArraySort(Context ctx, D domain, R range) { super(ctx, Native.mkArraySort(ctx.nCtx(), domain.getNativeObject(), range.getNativeObject())); } ArraySort(Context ctx, Sort[] domains, R range) { super(ctx, Native.mkArraySortN(ctx.nCtx(), domains.length, AST.arrayToNative(domains), range.getNativeObject())); } };
1,735
20.974684
94
java
z3
z3-master/src/api/java/AstMapDecRefQueue.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: AstMapDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; class ASTMapDecRefQueue extends IDecRefQueue<ASTMap> { public ASTMapDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.astMapDecRef(ctx.nCtx(), obj); } }
454
13.677419
56
java
z3
z3-master/src/api/java/AstVectorDecRefQueue.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: AstVectorDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; class ASTVectorDecRefQueue extends IDecRefQueue<ASTVector> { public ASTVectorDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.astVectorDecRef(ctx.nCtx(), obj); } }
469
14.16129
60
java
z3
z3-master/src/api/java/BitVecExpr.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: BitVecExpr.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Bit-vector expressions **/ public class BitVecExpr extends Expr<BitVecSort> { /** * The size of the sort of a bit-vector term. * @throws Z3Exception * @throws Z3Exception on error * @return an int **/ public int getSortSize() { return ((BitVecSort) getSort()).getSize(); } /** * Constructor for BitVecExpr **/ BitVecExpr(Context ctx, long obj) { super(ctx, obj); } }
672
13.955556
56
java
z3
z3-master/src/api/java/BitVecNum.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: BitVecNum.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import java.math.BigInteger; /** * Bit-vector numerals **/ public class BitVecNum extends BitVecExpr { /** * Retrieve the int value. * * @throws Z3Exception **/ public int getInt() { Native.IntPtr res = new Native.IntPtr(); if (!Native.getNumeralInt(getContext().nCtx(), getNativeObject(), res)) { throw new Z3Exception("Numeral is not an int"); } return res.value; } /** * Retrieve the 64-bit int value. * * @throws Z3Exception **/ public long getLong() { Native.LongPtr res = new Native.LongPtr(); if (!Native.getNumeralInt64(getContext().nCtx(), getNativeObject(), res)) { throw new Z3Exception("Numeral is not a long"); } return res.value; } /** * Retrieve the BigInteger value. **/ public BigInteger getBigInteger() { return new BigInteger(this.toString()); } /** * Returns a decimal string representation of the numeral. **/ @Override public String toString() { return Native.getNumeralString(getContext().nCtx(), getNativeObject()); } /** * Returns a binary string representation of the numeral. **/ public String toBinaryString() { return Native.getNumeralBinaryString(getContext().nCtx(), getNativeObject()); } BitVecNum(Context ctx, long obj) { super(ctx, obj); } }
1,682
18.8
85
java
z3
z3-master/src/api/java/BitVecSort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: BitVecSort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Bit-vector sorts. **/ public class BitVecSort extends Sort { /** * The size of the bit-vector sort. * @throws Z3Exception on error * @return an int **/ public int getSize() { return Native.getBvSortSize(getContext().nCtx(), getNativeObject()); } BitVecSort(Context ctx, long obj) { super(ctx, obj); } };
588
13.725
76
java
z3
z3-master/src/api/java/BoolExpr.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: BoolExpr.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Boolean expressions **/ public class BoolExpr extends Expr<BoolSort> { /** * Constructor for BoolExpr * @throws Z3Exception * @throws Z3Exception on error **/ BoolExpr(Context ctx, long obj) { super(ctx, obj); } }
477
12.657143
56
java
z3
z3-master/src/api/java/BoolSort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: BoolSort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * A Boolean sort. **/ public class BoolSort extends Sort { BoolSort(Context ctx, long obj) { super(ctx, obj); { }} BoolSort(Context ctx) { super(ctx, Native.mkBoolSort(ctx.nCtx())); { }} };
415
13.857143
76
java
z3
z3-master/src/api/java/CharSort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: CharSort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * A Character sort **/ public class CharSort extends Sort { CharSort(Context ctx, long obj) { super(ctx, obj); } CharSort(Context ctx) { super(ctx, Native.mkCharSort(ctx.nCtx())); { }} }
431
11.705882
76
java
z3
z3-master/src/api/java/Constructor.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Constructor.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Constructors are used for datatype sorts. **/ public class Constructor<R> extends Z3Object { private final int n; Constructor(Context ctx, int n, long nativeObj) { super(ctx, nativeObj); this.n = n; } /** * The number of fields of the constructor. * @throws Z3Exception * @throws Z3Exception on error * @return an int **/ public int getNumFields() { return n; } /** * The function declaration of the constructor. * @throws Z3Exception * @throws Z3Exception on error **/ public FuncDecl<DatatypeSort<R>> ConstructorDecl() { Native.LongPtr constructor = new Native.LongPtr(); Native.LongPtr tester = new Native.LongPtr(); long[] accessors = new long[n]; Native.queryConstructor(getContext().nCtx(), getNativeObject(), n, constructor, tester, accessors); return new FuncDecl<>(getContext(), constructor.value); } /** * The function declaration of the tester. * @throws Z3Exception * @throws Z3Exception on error **/ public FuncDecl<BoolSort> getTesterDecl() { Native.LongPtr constructor = new Native.LongPtr(); Native.LongPtr tester = new Native.LongPtr(); long[] accessors = new long[n]; Native.queryConstructor(getContext().nCtx(), getNativeObject(), n, constructor, tester, accessors); return new FuncDecl<>(getContext(), tester.value); } /** * The function declarations of the accessors * @throws Z3Exception * @throws Z3Exception on error **/ public FuncDecl<?>[] getAccessorDecls() { Native.LongPtr constructor = new Native.LongPtr(); Native.LongPtr tester = new Native.LongPtr(); long[] accessors = new long[n]; Native.queryConstructor(getContext().nCtx(), getNativeObject(), n, constructor, tester, accessors); FuncDecl<?>[] t = new FuncDecl[n]; for (int i = 0; i < n; i++) t[i] = new FuncDecl<>(getContext(), accessors[i]); return t; } @Override void incRef() { // Datatype constructors are not reference counted. } @Override void addToReferenceQueue() { getContext().getConstructorDRQ().storeReference(getContext(), this); } static <R> Constructor<R> of(Context ctx, Symbol name, Symbol recognizer, Symbol[] fieldNames, Sort[] sorts, int[] sortRefs) { int n = AST.arrayLength(fieldNames); if (n != AST.arrayLength(sorts)) throw new Z3Exception( "Number of field names does not match number of sorts"); if (sortRefs != null && sortRefs.length != n) throw new Z3Exception( "Number of field names does not match number of sort refs"); if (sortRefs == null) sortRefs = new int[n]; long nativeObj = Native.mkConstructor(ctx.nCtx(), name.getNativeObject(), recognizer.getNativeObject(), n, Symbol.arrayToNative(fieldNames), Sort.arrayToNative(sorts), sortRefs); return new Constructor<>(ctx, n, nativeObj); } }
3,401
27.830508
107
java
z3
z3-master/src/api/java/ConstructorDecRefQueue.java
package com.microsoft.z3; public class ConstructorDecRefQueue extends IDecRefQueue<Constructor<?>> { public ConstructorDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.delConstructor(ctx.nCtx(), obj); } }
285
21
74
java
z3
z3-master/src/api/java/ConstructorList.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: ConstructorList.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Lists of constructors **/ public class ConstructorList<R> extends Z3Object { ConstructorList(Context ctx, long obj) { super(ctx, obj); } @Override void incRef() { // Constructor lists are not reference counted. } @Override void addToReferenceQueue() { getContext().getConstructorListDRQ().storeReference(getContext(), this); } ConstructorList(Context ctx, Constructor<R>[] constructors) { super(ctx, Native.mkConstructorList(ctx.nCtx(), constructors.length, Constructor.arrayToNative(constructors))); } }
845
17
80
java
z3
z3-master/src/api/java/ConstructorListDecRefQueue.java
package com.microsoft.z3; public class ConstructorListDecRefQueue extends IDecRefQueue<ConstructorList<?>> { public ConstructorListDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.delConstructorList(ctx.nCtx(), obj); } }
301
22.230769
82
java
z3
z3-master/src/api/java/Context.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Context.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import static com.microsoft.z3.Constructor.of; import com.microsoft.z3.enumerations.Z3_ast_print_mode; import java.util.Map; /** * The main interaction with Z3 happens via the Context. * For applications that spawn an unbounded number of contexts, * the proper use is within a try-with-resources * scope so that the Context object gets garbage collected in * a predictable way. Contexts maintain all data-structures * related to terms and formulas that are created relative * to them. **/ @SuppressWarnings("unchecked") public class Context implements AutoCloseable { private long m_ctx; static final Object creation_lock = new Object(); public Context () { synchronized (creation_lock) { m_ctx = Native.mkContextRc(0); init(); } } protected Context (long m_ctx) { synchronized (creation_lock) { this.m_ctx = m_ctx; init(); } } /** * Constructor. * Remarks: * The following parameters can be set: * - proof (Boolean) Enable proof generation * - debug_ref_count (Boolean) Enable debug support for Z3_ast reference counting * - trace (Boolean) Tracing support for VCC * - trace_file_name (String) Trace out file for VCC traces * - timeout (unsigned) default timeout (in milliseconds) used for solvers * - well_sorted_check type checker * - auto_config use heuristics to automatically select solver and configure it * - model model generation for solvers, this parameter can be overwritten when creating a solver * - model_validate validate models produced by solvers * - unsat_core unsat-core generation for solvers, this parameter can be overwritten when creating a solver * Note that in previous versions of Z3, this constructor was also used to set global and * module parameters. For this purpose we should now use {@code Global.setParameter} **/ public Context(Map<String, String> settings) { synchronized (creation_lock) { long cfg = Native.mkConfig(); for (Map.Entry<String, String> kv : settings.entrySet()) { Native.setParamValue(cfg, kv.getKey(), kv.getValue()); } m_ctx = Native.mkContextRc(cfg); Native.delConfig(cfg); init(); } } private void init() { setPrintMode(Z3_ast_print_mode.Z3_PRINT_SMTLIB2_COMPLIANT); Native.setInternalErrorHandler(m_ctx); } /** * Creates a new symbol using an integer. * Remarks: Not all integers can be passed to this function. * The legal range of unsigned integers is 0 to 2^30-1. **/ public IntSymbol mkSymbol(int i) { return new IntSymbol(this, i); } /** * Create a symbol using a string. **/ public StringSymbol mkSymbol(String name) { return new StringSymbol(this, name); } /** * Create an array of symbols. **/ Symbol[] mkSymbols(String[] names) { if (names == null) return new Symbol[0]; Symbol[] result = new Symbol[names.length]; for (int i = 0; i < names.length; ++i) result[i] = mkSymbol(names[i]); return result; } private BoolSort m_boolSort = null; private IntSort m_intSort = null; private RealSort m_realSort = null; private SeqSort<CharSort> m_stringSort = null; /** * Retrieves the Boolean sort of the context. **/ public BoolSort getBoolSort() { if (m_boolSort == null) { m_boolSort = new BoolSort(this); } return m_boolSort; } /** * Retrieves the Integer sort of the context. **/ public IntSort getIntSort() { if (m_intSort == null) { m_intSort = new IntSort(this); } return m_intSort; } /** * Retrieves the Real sort of the context. **/ public RealSort getRealSort() { if (m_realSort == null) { m_realSort = new RealSort(this); } return m_realSort; } /** * Create a new Boolean sort. **/ public BoolSort mkBoolSort() { return new BoolSort(this); } /** * Creates character sort object. **/ public CharSort mkCharSort() { return new CharSort(this); } /** * Retrieves the String sort of the context. **/ public SeqSort<CharSort> getStringSort() { if (m_stringSort == null) { m_stringSort = mkStringSort(); } return m_stringSort; } /** * Create a new uninterpreted sort. **/ public UninterpretedSort mkUninterpretedSort(Symbol s) { checkContextMatch(s); return new UninterpretedSort(this, s); } /** * Create a new uninterpreted sort. **/ public UninterpretedSort mkUninterpretedSort(String str) { return mkUninterpretedSort(mkSymbol(str)); } /** * Create a new integer sort. **/ public IntSort mkIntSort() { return new IntSort(this); } /** * Create a real sort. **/ public RealSort mkRealSort() { return new RealSort(this); } /** * Create a new bit-vector sort. **/ public BitVecSort mkBitVecSort(int size) { return new BitVecSort(this, Native.mkBvSort(nCtx(), size)); } /** * Create a new array sort. **/ public final <D extends Sort, R extends Sort> ArraySort<D, R> mkArraySort(D domain, R range) { checkContextMatch(domain); checkContextMatch(range); return new ArraySort<>(this, domain, range); } /** * Create a new array sort. **/ public final <R extends Sort> ArraySort<Sort, R> mkArraySort(Sort[] domains, R range) { checkContextMatch(domains); checkContextMatch(range); return new ArraySort<>(this, domains, range); } /** * Create a new string sort **/ public SeqSort<CharSort> mkStringSort() { return new SeqSort<>(this, Native.mkStringSort(nCtx())); } /** * Create a new sequence sort **/ public final <R extends Sort> SeqSort<R> mkSeqSort(R s) { return new SeqSort<>(this, Native.mkSeqSort(nCtx(), s.getNativeObject())); } /** * Create a new regular expression sort **/ public final <R extends Sort> ReSort<R> mkReSort(R s) { return new ReSort<>(this, Native.mkReSort(nCtx(), s.getNativeObject())); } /** * Create a new tuple sort. **/ public TupleSort mkTupleSort(Symbol name, Symbol[] fieldNames, Sort[] fieldSorts) { checkContextMatch(name); checkContextMatch(fieldNames); checkContextMatch(fieldSorts); return new TupleSort(this, name, fieldNames.length, fieldNames, fieldSorts); } /** * Create a new enumeration sort. **/ public final <R> EnumSort<R> mkEnumSort(Symbol name, Symbol... enumNames) { checkContextMatch(name); checkContextMatch(enumNames); return new EnumSort<>(this, name, enumNames); } /** * Create a new enumeration sort. **/ public final <R> EnumSort<R> mkEnumSort(String name, String... enumNames) { return new EnumSort<>(this, mkSymbol(name), mkSymbols(enumNames)); } /** * Create a new list sort. **/ public final <R extends Sort> ListSort<R> mkListSort(Symbol name, R elemSort) { checkContextMatch(name); checkContextMatch(elemSort); return new ListSort<>(this, name, elemSort); } /** * Create a new list sort. **/ public final <R extends Sort> ListSort<R> mkListSort(String name, R elemSort) { checkContextMatch(elemSort); return new ListSort<>(this, mkSymbol(name), elemSort); } /** * Create a new finite domain sort. **/ public final <R> FiniteDomainSort<R> mkFiniteDomainSort(Symbol name, long size) { checkContextMatch(name); return new FiniteDomainSort<>(this, name, size); } /** * Create a new finite domain sort. **/ public final <R> FiniteDomainSort<R> mkFiniteDomainSort(String name, long size) { return new FiniteDomainSort<>(this, mkSymbol(name), size); } /** * Create a datatype constructor. * @param name constructor name * @param recognizer name of recognizer function. * @param fieldNames names of the constructor fields. * @param sorts field sorts, 0 if the field sort refers to a recursive sort. * @param sortRefs reference to datatype sort that is an argument to the * constructor; if the corresponding sort reference is 0, then the value in sort_refs should be * an index referring to one of the recursive datatypes that is * declared. **/ public final <R> Constructor<R> mkConstructor(Symbol name, Symbol recognizer, Symbol[] fieldNames, Sort[] sorts, int[] sortRefs) { return of(this, name, recognizer, fieldNames, sorts, sortRefs); } /** * Create a datatype constructor. **/ public final <R> Constructor<R> mkConstructor(String name, String recognizer, String[] fieldNames, Sort[] sorts, int[] sortRefs) { return of(this, mkSymbol(name), mkSymbol(recognizer), mkSymbols(fieldNames), sorts, sortRefs); } /** * Create a new datatype sort. **/ public final <R> DatatypeSort<R> mkDatatypeSort(Symbol name, Constructor<R>[] constructors) { checkContextMatch(name); checkContextMatch(constructors); return new DatatypeSort<>(this, name, constructors); } /** * Create a new datatype sort. **/ public final <R> DatatypeSort<R> mkDatatypeSort(String name, Constructor<R>[] constructors) { checkContextMatch(constructors); return new DatatypeSort<>(this, mkSymbol(name), constructors); } /** * Create mutually recursive datatypes. * @param names names of datatype sorts * @param c list of constructors, one list per sort. **/ public DatatypeSort<Object>[] mkDatatypeSorts(Symbol[] names, Constructor<Object>[][] c) { checkContextMatch(names); int n = names.length; ConstructorList<Object>[] cla = new ConstructorList[n]; long[] n_constr = new long[n]; for (int i = 0; i < n; i++) { Constructor<Object>[] constructor = c[i]; checkContextMatch(constructor); cla[i] = new ConstructorList<>(this, constructor); n_constr[i] = cla[i].getNativeObject(); } long[] n_res = new long[n]; Native.mkDatatypes(nCtx(), n, Symbol.arrayToNative(names), n_res, n_constr); DatatypeSort<Object>[] res = new DatatypeSort[n]; for (int i = 0; i < n; i++) res[i] = new DatatypeSort<>(this, n_res[i]); return res; } /** * Create mutually recursive data-types. **/ public DatatypeSort<Object>[] mkDatatypeSorts(String[] names, Constructor<Object>[][] c) { return mkDatatypeSorts(mkSymbols(names), c); } /** * Update a datatype field at expression t with value v. * The function performs a record update at t. The field * that is passed in as argument is updated with value v, * the remaining fields of t are unchanged. **/ public final <F extends Sort, R extends Sort> Expr<R> mkUpdateField(FuncDecl<F> field, Expr<R> t, Expr<F> v) throws Z3Exception { return (Expr<R>) Expr.create(this, Native.datatypeUpdateField (nCtx(), field.getNativeObject(), t.getNativeObject(), v.getNativeObject())); } /** * Creates a new function declaration. **/ public final <R extends Sort> FuncDecl<R> mkFuncDecl(Symbol name, Sort[] domain, R range) { checkContextMatch(name); checkContextMatch(domain); checkContextMatch(range); return new FuncDecl<>(this, name, domain, range); } public final <R extends Sort> FuncDecl<R> mkPropagateFunction(Symbol name, Sort[] domain, R range) { checkContextMatch(name); checkContextMatch(domain); checkContextMatch(range); long f = Native.solverPropagateDeclare( this.nCtx(), name.getNativeObject(), AST.arrayLength(domain), AST.arrayToNative(domain), range.getNativeObject()); return new FuncDecl<>(this, f); } /** * Creates a new function declaration. **/ public final <R extends Sort> FuncDecl<R> mkFuncDecl(Symbol name, Sort domain, R range) { checkContextMatch(name); checkContextMatch(domain); checkContextMatch(range); Sort[] q = new Sort[] { domain }; return new FuncDecl<>(this, name, q, range); } /** * Creates a new function declaration. **/ public final <R extends Sort> FuncDecl<R> mkFuncDecl(String name, Sort[] domain, R range) { checkContextMatch(domain); checkContextMatch(range); return new FuncDecl<>(this, mkSymbol(name), domain, range); } /** * Creates a new function declaration. **/ public final <R extends Sort> FuncDecl<R> mkFuncDecl(String name, Sort domain, R range) { checkContextMatch(domain); checkContextMatch(range); Sort[] q = new Sort[] { domain }; return new FuncDecl<>(this, mkSymbol(name), q, range); } /** * Creates a new recursive function declaration. **/ public final <R extends Sort> FuncDecl<R> mkRecFuncDecl(Symbol name, Sort[] domain, R range) { checkContextMatch(name); checkContextMatch(domain); checkContextMatch(range); return new FuncDecl<>(this, name, domain, range, true); } /** * Bind a definition to a recursive function declaration. * The function must have previously been created using * MkRecFuncDecl. The body may contain recursive uses of the function or * other mutually recursive functions. */ public final <R extends Sort> void AddRecDef(FuncDecl<R> f, Expr<?>[] args, Expr<R> body) { checkContextMatch(f); checkContextMatch(args); checkContextMatch(body); long[] argsNative = AST.arrayToNative(args); Native.addRecDef(nCtx(), f.getNativeObject(), args.length, argsNative, body.getNativeObject()); } /** * Creates a fresh function declaration with a name prefixed with * {@code prefix}. * @see #mkFuncDecl(String,Sort,Sort) * @see #mkFuncDecl(String,Sort[],Sort) **/ public final <R extends Sort> FuncDecl<R> mkFreshFuncDecl(String prefix, Sort[] domain, R range) { checkContextMatch(domain); checkContextMatch(range); return new FuncDecl<>(this, prefix, domain, range); } /** * Creates a new constant function declaration. **/ public final <R extends Sort> FuncDecl<R> mkConstDecl(Symbol name, R range) { checkContextMatch(name); checkContextMatch(range); return new FuncDecl<>(this, name, null, range); } /** * Creates a new constant function declaration. **/ public final <R extends Sort> FuncDecl<R> mkConstDecl(String name, R range) { checkContextMatch(range); return new FuncDecl<>(this, mkSymbol(name), null, range); } /** * Creates a fresh constant function declaration with a name prefixed with * {@code prefix}. * @see #mkFuncDecl(String,Sort,Sort) * @see #mkFuncDecl(String,Sort[],Sort) **/ public final <R extends Sort> FuncDecl<R> mkFreshConstDecl(String prefix, R range) { checkContextMatch(range); return new FuncDecl<>(this, prefix, null, range); } /** * Creates a new bound variable. * @param index The de-Bruijn index of the variable * @param ty The sort of the variable **/ public final <R extends Sort> Expr<R> mkBound(int index, R ty) { return (Expr<R>) Expr.create(this, Native.mkBound(nCtx(), index, ty.getNativeObject())); } /** * Create a quantifier pattern. **/ @SafeVarargs public final Pattern mkPattern(Expr<?>... terms) { if (terms.length == 0) throw new Z3Exception("Cannot create a pattern from zero terms"); long[] termsNative = AST.arrayToNative(terms); return new Pattern(this, Native.mkPattern(nCtx(), terms.length, termsNative)); } /** * Creates a new Constant of sort {@code range} and named * {@code name}. **/ public final <R extends Sort> Expr<R> mkConst(Symbol name, R range) { checkContextMatch(name); checkContextMatch(range); return (Expr<R>) Expr.create( this, Native.mkConst(nCtx(), name.getNativeObject(), range.getNativeObject())); } /** * Creates a new Constant of sort {@code range} and named * {@code name}. **/ public final <R extends Sort> Expr<R> mkConst(String name, R range) { return mkConst(mkSymbol(name), range); } /** * Creates a fresh Constant of sort {@code range} and a name * prefixed with {@code prefix}. **/ public final <R extends Sort> Expr<R> mkFreshConst(String prefix, R range) { checkContextMatch(range); return (Expr<R>) Expr.create(this, Native.mkFreshConst(nCtx(), prefix, range.getNativeObject())); } /** * Creates a fresh constant from the FuncDecl {@code f}. * @param f A decl of a 0-arity function **/ public final <R extends Sort> Expr<R> mkConst(FuncDecl<R> f) { return mkApp(f, (Expr<?>[]) null); } /** * Create a Boolean constant. **/ public BoolExpr mkBoolConst(Symbol name) { return (BoolExpr) mkConst(name, getBoolSort()); } /** * Create a Boolean constant. **/ public BoolExpr mkBoolConst(String name) { return (BoolExpr) mkConst(mkSymbol(name), getBoolSort()); } /** * Creates an integer constant. **/ public IntExpr mkIntConst(Symbol name) { return (IntExpr) mkConst(name, getIntSort()); } /** * Creates an integer constant. **/ public IntExpr mkIntConst(String name) { return (IntExpr) mkConst(name, getIntSort()); } /** * Creates a real constant. **/ public RealExpr mkRealConst(Symbol name) { return (RealExpr) mkConst(name, getRealSort()); } /** * Creates a real constant. **/ public RealExpr mkRealConst(String name) { return (RealExpr) mkConst(name, getRealSort()); } /** * Creates a bit-vector constant. **/ public BitVecExpr mkBVConst(Symbol name, int size) { return (BitVecExpr) mkConst(name, mkBitVecSort(size)); } /** * Creates a bit-vector constant. **/ public BitVecExpr mkBVConst(String name, int size) { return (BitVecExpr) mkConst(name, mkBitVecSort(size)); } /** * Create a new function application. **/ @SafeVarargs public final <R extends Sort> Expr<R> mkApp(FuncDecl<R> f, Expr<?>... args) { checkContextMatch(f); checkContextMatch(args); return Expr.create(this, f, args); } /** * The true Term. **/ public BoolExpr mkTrue() { return new BoolExpr(this, Native.mkTrue(nCtx())); } /** * The false Term. **/ public BoolExpr mkFalse() { return new BoolExpr(this, Native.mkFalse(nCtx())); } /** * Creates a Boolean value. **/ public BoolExpr mkBool(boolean value) { return value ? mkTrue() : mkFalse(); } /** * Creates the equality {@code x = y} **/ public BoolExpr mkEq(Expr<?> x, Expr<?> y) { checkContextMatch(x); checkContextMatch(y); return new BoolExpr(this, Native.mkEq(nCtx(), x.getNativeObject(), y.getNativeObject())); } /** * Creates a {@code distinct} term. **/ @SafeVarargs public final BoolExpr mkDistinct(Expr<?>... args) { checkContextMatch(args); return new BoolExpr(this, Native.mkDistinct(nCtx(), args.length, AST.arrayToNative(args))); } /** * Create an expression representing {@code not(a)}. **/ public final BoolExpr mkNot(Expr<BoolSort> a) { checkContextMatch(a); return new BoolExpr(this, Native.mkNot(nCtx(), a.getNativeObject())); } /** * Create an expression representing an if-then-else: * {@code ite(t1, t2, t3)}. * @param t1 An expression with Boolean sort * @param t2 An expression * @param t3 An expression with the same sort as {@code t2} **/ public final <R extends Sort> Expr<R> mkITE(Expr<BoolSort> t1, Expr<? extends R> t2, Expr<? extends R> t3) { checkContextMatch(t1); checkContextMatch(t2); checkContextMatch(t3); return (Expr<R>) Expr.create(this, Native.mkIte(nCtx(), t1.getNativeObject(), t2.getNativeObject(), t3.getNativeObject())); } /** * Create an expression representing {@code t1 iff t2}. **/ public BoolExpr mkIff(Expr<BoolSort> t1, Expr<BoolSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkIff(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create an expression representing {@code t1 -> t2}. **/ public BoolExpr mkImplies(Expr<BoolSort> t1, Expr<BoolSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkImplies(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create an expression representing {@code t1 xor t2}. **/ public BoolExpr mkXor(Expr<BoolSort> t1, Expr<BoolSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkXor(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create an expression representing {@code t[0] and t[1] and ...}. **/ @SafeVarargs public final BoolExpr mkAnd(Expr<BoolSort>... t) { checkContextMatch(t); return new BoolExpr(this, Native.mkAnd(nCtx(), t.length, AST.arrayToNative(t))); } /** * Create an expression representing {@code t[0] or t[1] or ...}. **/ @SafeVarargs public final BoolExpr mkOr(Expr<BoolSort>... t) { checkContextMatch(t); return new BoolExpr(this, Native.mkOr(nCtx(), t.length, AST.arrayToNative(t))); } /** * Create an expression representing {@code t[0] + t[1] + ...}. **/ @SafeVarargs public final <R extends ArithSort> ArithExpr<R> mkAdd(Expr<? extends R>... t) { checkContextMatch(t); return (ArithExpr<R>) Expr.create(this, Native.mkAdd(nCtx(), t.length, AST.arrayToNative(t))); } /** * Create an expression representing {@code t[0] * t[1] * ...}. **/ @SafeVarargs public final <R extends ArithSort> ArithExpr<R> mkMul(Expr<? extends R>... t) { checkContextMatch(t); return (ArithExpr<R>) Expr.create(this, Native.mkMul(nCtx(), t.length, AST.arrayToNative(t))); } /** * Create an expression representing {@code t[0] - t[1] - ...}. **/ @SafeVarargs public final <R extends ArithSort> ArithExpr<R> mkSub(Expr<? extends R>... t) { checkContextMatch(t); return (ArithExpr<R>) Expr.create(this, Native.mkSub(nCtx(), t.length, AST.arrayToNative(t))); } /** * Create an expression representing {@code -t}. **/ public final <R extends ArithSort> ArithExpr<R> mkUnaryMinus(Expr<R> t) { checkContextMatch(t); return (ArithExpr<R>) Expr.create(this, Native.mkUnaryMinus(nCtx(), t.getNativeObject())); } /** * Create an expression representing {@code t1 / t2}. **/ public final <R extends ArithSort> ArithExpr<R> mkDiv(Expr<? extends R> t1, Expr<? extends R> t2) { checkContextMatch(t1); checkContextMatch(t2); return (ArithExpr<R>) Expr.create(this, Native.mkDiv(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create an expression representing {@code t1 mod t2}. * Remarks: The * arguments must have int type. **/ public IntExpr mkMod(Expr<IntSort> t1, Expr<IntSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new IntExpr(this, Native.mkMod(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create an expression representing {@code t1 rem t2}. * Remarks: The * arguments must have int type. **/ public IntExpr mkRem(Expr<IntSort> t1, Expr<IntSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new IntExpr(this, Native.mkRem(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create an expression representing {@code t1 ^ t2}. **/ public final <R extends ArithSort> ArithExpr<R> mkPower(Expr<? extends R> t1, Expr<? extends R> t2) { checkContextMatch(t1); checkContextMatch(t2); return (ArithExpr<R>) Expr.create( this, Native.mkPower(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create an expression representing {@code t1 &lt; t2} **/ public BoolExpr mkLt(Expr<? extends ArithSort> t1, Expr<? extends ArithSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkLt(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create an expression representing {@code t1 &lt;= t2} **/ public BoolExpr mkLe(Expr<? extends ArithSort> t1, Expr<? extends ArithSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkLe(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create an expression representing {@code t1 &gt; t2} **/ public BoolExpr mkGt(Expr<? extends ArithSort> t1, Expr<? extends ArithSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkGt(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create an expression representing {@code t1 &gt;= t2} **/ public BoolExpr mkGe(Expr<? extends ArithSort> t1, Expr<? extends ArithSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkGe(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Coerce an integer to a real. * Remarks: There is also a converse operation * exposed. It follows the semantics prescribed by the SMT-LIB standard. * * You can take the floor of a real by creating an auxiliary integer Term * {@code k} and asserting * {@code MakeInt2Real(k) &lt;= t1 &lt; MkInt2Real(k)+1}. The argument * must be of integer sort. **/ public RealExpr mkInt2Real(Expr<IntSort> t) { checkContextMatch(t); return new RealExpr(this, Native.mkInt2real(nCtx(), t.getNativeObject())); } /** * Coerce a real to an integer. * Remarks: The semantics of this function * follows the SMT-LIB standard for the function to_int. The argument must * be of real sort. **/ public IntExpr mkReal2Int(Expr<RealSort> t) { checkContextMatch(t); return new IntExpr(this, Native.mkReal2int(nCtx(), t.getNativeObject())); } /** * Creates an expression that checks whether a real number is an integer. **/ public BoolExpr mkIsInteger(Expr<RealSort> t) { checkContextMatch(t); return new BoolExpr(this, Native.mkIsInt(nCtx(), t.getNativeObject())); } /** * Bitwise negation. * Remarks: The argument must have a bit-vector * sort. **/ public BitVecExpr mkBVNot(Expr<BitVecSort> t) { checkContextMatch(t); return new BitVecExpr(this, Native.mkBvnot(nCtx(), t.getNativeObject())); } /** * Take conjunction of bits in a vector, return vector of length 1. * * Remarks: The argument must have a bit-vector sort. **/ public BitVecExpr mkBVRedAND(Expr<BitVecSort> t) { checkContextMatch(t); return new BitVecExpr(this, Native.mkBvredand(nCtx(), t.getNativeObject())); } /** * Take disjunction of bits in a vector, return vector of length 1. * * Remarks: The argument must have a bit-vector sort. **/ public BitVecExpr mkBVRedOR(Expr<BitVecSort> t) { checkContextMatch(t); return new BitVecExpr(this, Native.mkBvredor(nCtx(), t.getNativeObject())); } /** * Bitwise conjunction. * Remarks: The arguments must have a bit-vector * sort. **/ public BitVecExpr mkBVAND(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkBvand(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Bitwise disjunction. * Remarks: The arguments must have a bit-vector * sort. **/ public BitVecExpr mkBVOR(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkBvor(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Bitwise XOR. * Remarks: The arguments must have a bit-vector * sort. **/ public BitVecExpr mkBVXOR(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkBvxor(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Bitwise NAND. * Remarks: The arguments must have a bit-vector * sort. **/ public BitVecExpr mkBVNAND(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkBvnand(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Bitwise NOR. * Remarks: The arguments must have a bit-vector * sort. **/ public BitVecExpr mkBVNOR(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkBvnor(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Bitwise XNOR. * Remarks: The arguments must have a bit-vector * sort. **/ public BitVecExpr mkBVXNOR(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkBvxnor(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Standard two's complement unary minus. * Remarks: The arguments must have a * bit-vector sort. **/ public BitVecExpr mkBVNeg(Expr<BitVecSort> t) { checkContextMatch(t); return new BitVecExpr(this, Native.mkBvneg(nCtx(), t.getNativeObject())); } /** * Two's complement addition. * Remarks: The arguments must have the same * bit-vector sort. **/ public BitVecExpr mkBVAdd(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkBvadd(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Two's complement subtraction. * Remarks: The arguments must have the same * bit-vector sort. **/ public BitVecExpr mkBVSub(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkBvsub(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Two's complement multiplication. * Remarks: The arguments must have the * same bit-vector sort. **/ public BitVecExpr mkBVMul(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkBvmul(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Unsigned division. * Remarks: It is defined as the floor of * {@code t1/t2} if \c t2 is different from zero. If {@code t2} is * zero, then the result is undefined. The arguments must have the same * bit-vector sort. **/ public BitVecExpr mkBVUDiv(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkBvudiv(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Signed division. * Remarks: It is defined in the following way: * * - The \c floor of {@code t1/t2} if \c t2 is different from zero, and * {@code t1*t2 >= 0}. * * - The \c ceiling of {@code t1/t2} if \c t2 is different from zero, * and {@code t1*t2 &lt; 0}. * * If {@code t2} is zero, then the result is undefined. The arguments * must have the same bit-vector sort. **/ public BitVecExpr mkBVSDiv(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkBvsdiv(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Unsigned remainder. * Remarks: It is defined as * {@code t1 - (t1 /u t2) * t2}, where {@code /u} represents * unsigned division. If {@code t2} is zero, then the result is * undefined. The arguments must have the same bit-vector sort. **/ public BitVecExpr mkBVURem(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkBvurem(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Signed remainder. * Remarks: It is defined as * {@code t1 - (t1 /s t2) * t2}, where {@code /s} represents * signed division. The most significant bit (sign) of the result is equal * to the most significant bit of \c t1. * * If {@code t2} is zero, then the result is undefined. The arguments * must have the same bit-vector sort. **/ public BitVecExpr mkBVSRem(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkBvsrem(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Two's complement signed remainder (sign follows divisor). * Remarks: If * {@code t2} is zero, then the result is undefined. The arguments must * have the same bit-vector sort. **/ public BitVecExpr mkBVSMod(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkBvsmod(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Unsigned less-than * Remarks: The arguments must have the same bit-vector * sort. **/ public BoolExpr mkBVULT(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkBvult(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Two's complement signed less-than * Remarks: The arguments must have the * same bit-vector sort. **/ public BoolExpr mkBVSLT(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkBvslt(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Unsigned less-than or equal to. * Remarks: The arguments must have the * same bit-vector sort. **/ public BoolExpr mkBVULE(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkBvule(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Two's complement signed less-than or equal to. * Remarks: The arguments * must have the same bit-vector sort. **/ public BoolExpr mkBVSLE(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkBvsle(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Unsigned greater than or equal to. * Remarks: The arguments must have the * same bit-vector sort. **/ public BoolExpr mkBVUGE(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkBvuge(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Two's complement signed greater than or equal to. * Remarks: The arguments * must have the same bit-vector sort. **/ public BoolExpr mkBVSGE(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkBvsge(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Unsigned greater-than. * Remarks: The arguments must have the same * bit-vector sort. **/ public BoolExpr mkBVUGT(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkBvugt(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Two's complement signed greater-than. * Remarks: The arguments must have * the same bit-vector sort. **/ public BoolExpr mkBVSGT(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkBvsgt(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Bit-vector concatenation. * Remarks: The arguments must have a bit-vector * sort. * * @return The result is a bit-vector of size {@code n1+n2}, where * {@code n1} ({@code n2}) is the size of {@code t1} * ({@code t2}). * **/ public BitVecExpr mkConcat(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkConcat(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Bit-vector extraction. * Remarks: Extract the bits {@code high} * down to {@code low} from a bitvector of size {@code m} to * yield a new bitvector of size {@code n}, where * {@code n = high - low + 1}. The argument {@code t} must * have a bit-vector sort. **/ public BitVecExpr mkExtract(int high, int low, Expr<BitVecSort> t) { checkContextMatch(t); return new BitVecExpr(this, Native.mkExtract(nCtx(), high, low, t.getNativeObject())); } /** * Bit-vector sign extension. * Remarks: Sign-extends the given bit-vector to * the (signed) equivalent bitvector of size {@code m+i}, where \c m is * the size of the given bit-vector. The argument {@code t} must * have a bit-vector sort. **/ public BitVecExpr mkSignExt(int i, Expr<BitVecSort> t) { checkContextMatch(t); return new BitVecExpr(this, Native.mkSignExt(nCtx(), i, t.getNativeObject())); } /** * Bit-vector zero extension. * Remarks: Extend the given bit-vector with * zeros to the (unsigned) equivalent bitvector of size {@code m+i}, * where \c m is the size of the given bit-vector. The argument {@code t} * must have a bit-vector sort. **/ public BitVecExpr mkZeroExt(int i, Expr<BitVecSort> t) { checkContextMatch(t); return new BitVecExpr(this, Native.mkZeroExt(nCtx(), i, t.getNativeObject())); } /** * Bit-vector repetition. * Remarks: The argument {@code t} must * have a bit-vector sort. **/ public BitVecExpr mkRepeat(int i, Expr<BitVecSort> t) { checkContextMatch(t); return new BitVecExpr(this, Native.mkRepeat(nCtx(), i, t.getNativeObject())); } /** * Shift left. * Remarks: It is equivalent to multiplication by * {@code 2^x} where \c x is the value of {@code t2}. * * NB. The semantics of shift operations varies between environments. This * definition does not necessarily capture directly the semantics of the * programming language or assembly architecture you are modeling. * * The arguments must have a bit-vector sort. **/ public BitVecExpr mkBVSHL(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkBvshl(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Logical shift right * Remarks: It is equivalent to unsigned division by * {@code 2^x} where \c x is the value of {@code t2}. * * NB. The semantics of shift operations varies between environments. This * definition does not necessarily capture directly the semantics of the * programming language or assembly architecture you are modeling. * * The arguments must have a bit-vector sort. **/ public BitVecExpr mkBVLSHR(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkBvlshr(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Arithmetic shift right * Remarks: It is like logical shift right except * that the most significant bits of the result always copy the most * significant bit of the second argument. * * NB. The semantics of shift operations varies between environments. This * definition does not necessarily capture directly the semantics of the * programming language or assembly architecture you are modeling. * * The arguments must have a bit-vector sort. **/ public BitVecExpr mkBVASHR(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkBvashr(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Rotate Left. * Remarks: Rotate bits of \c t to the left \c i times. The * argument {@code t} must have a bit-vector sort. **/ public BitVecExpr mkBVRotateLeft(int i, Expr<BitVecSort> t) { checkContextMatch(t); return new BitVecExpr(this, Native.mkRotateLeft(nCtx(), i, t.getNativeObject())); } /** * Rotate Right. * Remarks: Rotate bits of \c t to the right \c i times. The * argument {@code t} must have a bit-vector sort. **/ public BitVecExpr mkBVRotateRight(int i, Expr<BitVecSort> t) { checkContextMatch(t); return new BitVecExpr(this, Native.mkRotateRight(nCtx(), i, t.getNativeObject())); } /** * Rotate Left. * Remarks: Rotate bits of {@code t1} to the left * {@code t2} times. The arguments must have the same bit-vector * sort. **/ public BitVecExpr mkBVRotateLeft(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkExtRotateLeft(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Rotate Right. * Remarks: Rotate bits of {@code t1} to the * right{@code t2} times. The arguments must have the same * bit-vector sort. **/ public BitVecExpr mkBVRotateRight(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BitVecExpr(this, Native.mkExtRotateRight(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create an {@code n} bit bit-vector from the integer argument * {@code t}. * Remarks: NB. This function is essentially treated * as uninterpreted. So you cannot expect Z3 to precisely reflect the * semantics of this function when solving constraints with this function. * * The argument must be of integer sort. **/ public BitVecExpr mkInt2BV(int n, Expr<IntSort> t) { checkContextMatch(t); return new BitVecExpr(this, Native.mkInt2bv(nCtx(), n, t.getNativeObject())); } /** * Create an integer from the bit-vector argument {@code t}. * Remarks: If \c is_signed is false, then the bit-vector \c t1 is treated * as unsigned. So the result is non-negative and in the range * {@code [0..2^N-1]}, where N are the number of bits in {@code t}. * If \c is_signed is true, \c t1 is treated as a signed * bit-vector. * * NB. This function is essentially treated as uninterpreted. So you cannot * expect Z3 to precisely reflect the semantics of this function when * solving constraints with this function. * * The argument must be of bit-vector sort. **/ public IntExpr mkBV2Int(Expr<BitVecSort> t, boolean signed) { checkContextMatch(t); return new IntExpr(this, Native.mkBv2int(nCtx(), t.getNativeObject(), (signed))); } /** * Create a predicate that checks that the bit-wise addition does not * overflow. * Remarks: The arguments must be of bit-vector sort. **/ public BoolExpr mkBVAddNoOverflow(Expr<BitVecSort> t1, Expr<BitVecSort> t2, boolean isSigned) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkBvaddNoOverflow(nCtx(), t1 .getNativeObject(), t2.getNativeObject(), (isSigned))); } /** * Create a predicate that checks that the bit-wise addition does not * underflow. * Remarks: The arguments must be of bit-vector sort. **/ public BoolExpr mkBVAddNoUnderflow(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkBvaddNoUnderflow(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create a predicate that checks that the bit-wise subtraction does not * overflow. * Remarks: The arguments must be of bit-vector sort. **/ public BoolExpr mkBVSubNoOverflow(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkBvsubNoOverflow(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create a predicate that checks that the bit-wise subtraction does not * underflow. * Remarks: The arguments must be of bit-vector sort. **/ public BoolExpr mkBVSubNoUnderflow(Expr<BitVecSort> t1, Expr<BitVecSort> t2, boolean isSigned) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkBvsubNoUnderflow(nCtx(), t1 .getNativeObject(), t2.getNativeObject(), (isSigned))); } /** * Create a predicate that checks that the bit-wise signed division does not * overflow. * Remarks: The arguments must be of bit-vector sort. **/ public BoolExpr mkBVSDivNoOverflow(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkBvsdivNoOverflow(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create a predicate that checks that the bit-wise negation does not * overflow. * Remarks: The arguments must be of bit-vector sort. **/ public BoolExpr mkBVNegNoOverflow(Expr<BitVecSort> t) { checkContextMatch(t); return new BoolExpr(this, Native.mkBvnegNoOverflow(nCtx(), t.getNativeObject())); } /** * Create a predicate that checks that the bit-wise multiplication does not * overflow. * Remarks: The arguments must be of bit-vector sort. **/ public BoolExpr mkBVMulNoOverflow(Expr<BitVecSort> t1, Expr<BitVecSort> t2, boolean isSigned) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkBvmulNoOverflow(nCtx(), t1 .getNativeObject(), t2.getNativeObject(), (isSigned))); } /** * Create a predicate that checks that the bit-wise multiplication does not * underflow. * Remarks: The arguments must be of bit-vector sort. **/ public BoolExpr mkBVMulNoUnderflow(Expr<BitVecSort> t1, Expr<BitVecSort> t2) { checkContextMatch(t1); checkContextMatch(t2); return new BoolExpr(this, Native.mkBvmulNoUnderflow(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create an array constant. **/ public final <D extends Sort, R extends Sort> ArrayExpr<D, R> mkArrayConst(Symbol name, D domain, R range) { return (ArrayExpr<D, R>) mkConst(name, mkArraySort(domain, range)); } /** * Create an array constant. **/ public final <D extends Sort, R extends Sort> ArrayExpr<D, R> mkArrayConst(String name, D domain, R range) { return (ArrayExpr<D, R>) mkConst(mkSymbol(name), mkArraySort(domain, range)); } /** * Array read. * Remarks: The argument {@code a} is the array and * {@code i} is the index of the array that gets read. * * The node {@code a} must have an array sort * {@code [domain -> range]}, and {@code i} must have the sort * {@code domain}. The sort of the result is {@code range}. * * @see #mkArraySort(Sort[], R) * @see #mkStore(Expr<ArraySort<D, R>> a, Expr<D> i, Expr<R> v) **/ public final <D extends Sort, R extends Sort> Expr<R> mkSelect(Expr<ArraySort<D, R>> a, Expr<D> i) { checkContextMatch(a); checkContextMatch(i); return (Expr<R>) Expr.create( this, Native.mkSelect(nCtx(), a.getNativeObject(), i.getNativeObject())); } /** * Array read. * Remarks: The argument {@code a} is the array and * {@code args} are the indices of the array that gets read. * * The node {@code a} must have an array sort * {@code [domains -> range]}, and {@code args} must have the sorts * {@code domains}. The sort of the result is {@code range}. * * @see #mkArraySort(Sort[], R) * @see #mkStore(Expr<ArraySort<D, R>> a, Expr<D> i, Expr<R> v) **/ public final <R extends Sort> Expr<R> mkSelect(Expr<ArraySort<Sort, R>> a, Expr<?>[] args) { checkContextMatch(a); checkContextMatch(args); return (Expr<R>) Expr.create( this, Native.mkSelectN(nCtx(), a.getNativeObject(), args.length, AST.arrayToNative(args))); } /** * Array update. * Remarks: The node {@code a} must have an array sort * {@code [domain -> range]}, {@code i} must have sort * {@code domain}, {@code v} must have sort range. The sort of the * result is {@code [domain -> range]}. The semantics of this function * is given by the theory of arrays described in the SMT-LIB standard. See * http://smtlib.org for more details. The result of this function is an * array that is equal to {@code a} (with respect to * {@code select}) on all indices except for {@code i}, where it * maps to {@code v} (and the {@code select} of {@code a} * with respect to {@code i} may be a different value). * @see #mkArraySort(Sort[], R) * @see #mkSelect(Expr<ArraySort<D, R>> a, Expr<D> i) **/ public final <D extends Sort, R extends Sort> ArrayExpr<D, R> mkStore(Expr<ArraySort<D, R>> a, Expr<D> i, Expr<R> v) { checkContextMatch(a); checkContextMatch(i); checkContextMatch(v); return new ArrayExpr<>(this, Native.mkStore(nCtx(), a.getNativeObject(), i.getNativeObject(), v.getNativeObject())); } /** * Array update. * Remarks: The node {@code a} must have an array sort * {@code [domains -> range]}, {@code i} must have sort * {@code domain}, {@code v} must have sort range. The sort of the * result is {@code [domains -> range]}. The semantics of this function * is given by the theory of arrays described in the SMT-LIB standard. See * http://smtlib.org for more details. The result of this function is an * array that is equal to {@code a} (with respect to * {@code select}) on all indices except for {@code args}, where it * maps to {@code v} (and the {@code select} of {@code a} * with respect to {@code args} may be a different value). * @see #mkArraySort(Sort[], R) * @see #mkSelect(Expr<ArraySort<D, R>> a, Expr<D> i) **/ public final <R extends Sort> ArrayExpr<Sort, R> mkStore(Expr<ArraySort<Sort, R>> a, Expr<?>[] args, Expr<R> v) { checkContextMatch(a); checkContextMatch(args); checkContextMatch(v); return new ArrayExpr<>(this, Native.mkStoreN(nCtx(), a.getNativeObject(), args.length, AST.arrayToNative(args), v.getNativeObject())); } /** * Create a constant array. * Remarks: The resulting term is an array, such * that a {@code select} on an arbitrary index produces the value * {@code v}. * @see #mkArraySort(Sort[], R) * @see #mkSelect(Expr<ArraySort<D, R>> a, Expr<D> i) * **/ public final <D extends Sort, R extends Sort> ArrayExpr<D, R> mkConstArray(D domain, Expr<R> v) { checkContextMatch(domain); checkContextMatch(v); return new ArrayExpr<>(this, Native.mkConstArray(nCtx(), domain.getNativeObject(), v.getNativeObject())); } /** * Maps f on the argument arrays. * Remarks: Each element of * {@code args} must be of an array sort * {@code [domain_i -> range_i]}. The function declaration * {@code f} must have type {@code range_1 .. range_n -> range}. * {@code v} must have sort range. The sort of the result is * {@code [domain_i -> range]}. * @see #mkArraySort(Sort[], R) * @see #mkSelect(Expr<ArraySort<D, R>> a, Expr<D> i) * @see #mkStore(Expr<ArraySort<D, R>> a, Expr<D> i, Expr<R> v) **/ @SafeVarargs public final <D extends Sort, R1 extends Sort, R2 extends Sort> ArrayExpr<D, R2> mkMap(FuncDecl<R2> f, Expr<ArraySort<D, R1>>... args) { checkContextMatch(f); checkContextMatch(args); return (ArrayExpr<D, R2>) Expr.create(this, Native.mkMap(nCtx(), f.getNativeObject(), AST.arrayLength(args), AST.arrayToNative(args))); } /** * Access the array default value. * Remarks: Produces the default range * value, for arrays that can be represented as finite maps with a default * range value. **/ public final <D extends Sort, R extends Sort> Expr<R> mkTermArray(Expr<ArraySort<D, R>> array) { checkContextMatch(array); return (Expr<R>) Expr.create(this, Native.mkArrayDefault(nCtx(), array.getNativeObject())); } /** * Create Extentionality index. Two arrays are equal if and only if they are equal on the index returned by MkArrayExt. **/ public final <D extends Sort, R extends Sort> Expr<D> mkArrayExt(Expr<ArraySort<D, R>> arg1, Expr<ArraySort<D, R>> arg2) { checkContextMatch(arg1); checkContextMatch(arg2); return (Expr<D>) Expr.create(this, Native.mkArrayExt(nCtx(), arg1.getNativeObject(), arg2.getNativeObject())); } /** * Create a set type. **/ public final <D extends Sort> SetSort<D> mkSetSort(D ty) { checkContextMatch(ty); return new SetSort<>(this, ty); } /** * Create an empty set. **/ public final <D extends Sort> ArrayExpr<D, BoolSort> mkEmptySet(D domain) { checkContextMatch(domain); return (ArrayExpr<D, BoolSort>) Expr.create(this, Native.mkEmptySet(nCtx(), domain.getNativeObject())); } /** * Create the full set. **/ public final <D extends Sort> ArrayExpr<D, BoolSort> mkFullSet(D domain) { checkContextMatch(domain); return (ArrayExpr<D, BoolSort>) Expr.create(this, Native.mkFullSet(nCtx(), domain.getNativeObject())); } /** * Add an element to the set. **/ public final <D extends Sort> ArrayExpr<D, BoolSort> mkSetAdd(Expr<ArraySort<D, BoolSort>> set, Expr<D> element) { checkContextMatch(set); checkContextMatch(element); return (ArrayExpr<D, BoolSort>) Expr.create(this, Native.mkSetAdd(nCtx(), set.getNativeObject(), element.getNativeObject())); } /** * Remove an element from a set. **/ public final <D extends Sort> ArrayExpr<D, BoolSort> mkSetDel(Expr<ArraySort<D, BoolSort>> set, Expr<D> element) { checkContextMatch(set); checkContextMatch(element); return (ArrayExpr<D, BoolSort>)Expr.create(this, Native.mkSetDel(nCtx(), set.getNativeObject(), element.getNativeObject())); } /** * Take the union of a list of sets. **/ @SafeVarargs public final <D extends Sort> ArrayExpr<D, BoolSort> mkSetUnion(Expr<ArraySort<D, BoolSort>>... args) { checkContextMatch(args); return (ArrayExpr<D, BoolSort>)Expr.create(this, Native.mkSetUnion(nCtx(), args.length, AST.arrayToNative(args))); } /** * Take the intersection of a list of sets. **/ @SafeVarargs public final <D extends Sort> ArrayExpr<D, BoolSort> mkSetIntersection(Expr<ArraySort<D, BoolSort>>... args) { checkContextMatch(args); return (ArrayExpr<D, BoolSort>) Expr.create(this, Native.mkSetIntersect(nCtx(), args.length, AST.arrayToNative(args))); } /** * Take the difference between two sets. **/ public final <D extends Sort> ArrayExpr<D, BoolSort> mkSetDifference(Expr<ArraySort<D, BoolSort>> arg1, Expr<ArraySort<D, BoolSort>> arg2) { checkContextMatch(arg1); checkContextMatch(arg2); return (ArrayExpr<D, BoolSort>) Expr.create(this, Native.mkSetDifference(nCtx(), arg1.getNativeObject(), arg2.getNativeObject())); } /** * Take the complement of a set. **/ public final <D extends Sort> ArrayExpr<D, BoolSort> mkSetComplement(Expr<ArraySort<D, BoolSort>> arg) { checkContextMatch(arg); return (ArrayExpr<D, BoolSort>)Expr.create(this, Native.mkSetComplement(nCtx(), arg.getNativeObject())); } /** * Check for set membership. **/ public final <D extends Sort> BoolExpr mkSetMembership(Expr<D> elem, Expr<ArraySort<D, BoolSort>> set) { checkContextMatch(elem); checkContextMatch(set); return (BoolExpr) Expr.create(this, Native.mkSetMember(nCtx(), elem.getNativeObject(), set.getNativeObject())); } /** * Check for subsetness of sets. **/ public final <D extends Sort> BoolExpr mkSetSubset(Expr<ArraySort<D, BoolSort>> arg1, Expr<ArraySort<D, BoolSort>> arg2) { checkContextMatch(arg1); checkContextMatch(arg2); return (BoolExpr) Expr.create(this, Native.mkSetSubset(nCtx(), arg1.getNativeObject(), arg2.getNativeObject())); } /** * Sequences, Strings and regular expressions. */ /** * Create the empty sequence. */ public final <R extends Sort> SeqExpr<R> mkEmptySeq(R s) { checkContextMatch(s); return (SeqExpr<R>) Expr.create(this, Native.mkSeqEmpty(nCtx(), s.getNativeObject())); } /** * Create the singleton sequence. */ public final <R extends Sort> SeqExpr<R> mkUnit(Expr<R> elem) { checkContextMatch(elem); return (SeqExpr<R>) Expr.create(this, Native.mkSeqUnit(nCtx(), elem.getNativeObject())); } /** * Create a string constant. */ public SeqExpr<CharSort> mkString(String s) { StringBuilder buf = new StringBuilder(); for (int i = 0; i < s.length(); ++i) { int code = s.codePointAt(i); if (code <= 32 || 127 < code) buf.append(String.format("\\u{%x}", code)); else buf.append(s.charAt(i)); } return (SeqExpr<CharSort>) Expr.create(this, Native.mkString(nCtx(), buf.toString())); } /** * Convert an integer expression to a string. */ public SeqExpr<CharSort> intToString(Expr<IntSort> e) { return (SeqExpr<CharSort>) Expr.create(this, Native.mkIntToStr(nCtx(), e.getNativeObject())); } /** * Convert an unsigned bitvector expression to a string. */ public SeqExpr<CharSort> ubvToString(Expr<BitVecSort> e) { return (SeqExpr<CharSort>) Expr.create(this, Native.mkUbvToStr(nCtx(), e.getNativeObject())); } /** * Convert an signed bitvector expression to a string. */ public SeqExpr<CharSort> sbvToString(Expr<BitVecSort> e) { return (SeqExpr<CharSort>) Expr.create(this, Native.mkSbvToStr(nCtx(), e.getNativeObject())); } /** * Convert an integer expression to a string. */ public IntExpr stringToInt(Expr<SeqSort<CharSort>> e) { return (IntExpr) Expr.create(this, Native.mkStrToInt(nCtx(), e.getNativeObject())); } /** * Concatenate sequences. */ @SafeVarargs public final <R extends Sort> SeqExpr<R> mkConcat(Expr<SeqSort<R>>... t) { checkContextMatch(t); return (SeqExpr<R>) Expr.create(this, Native.mkSeqConcat(nCtx(), t.length, AST.arrayToNative(t))); } /** * Retrieve the length of a given sequence. */ public final <R extends Sort> IntExpr mkLength(Expr<SeqSort<R>> s) { checkContextMatch(s); return (IntExpr) Expr.create(this, Native.mkSeqLength(nCtx(), s.getNativeObject())); } /** * Check for sequence prefix. */ public final <R extends Sort> BoolExpr mkPrefixOf(Expr<SeqSort<R>> s1, Expr<SeqSort<R>> s2) { checkContextMatch(s1, s2); return (BoolExpr) Expr.create(this, Native.mkSeqPrefix(nCtx(), s1.getNativeObject(), s2.getNativeObject())); } /** * Check for sequence suffix. */ public final <R extends Sort> BoolExpr mkSuffixOf(Expr<SeqSort<R>> s1, Expr<SeqSort<R>> s2) { checkContextMatch(s1, s2); return (BoolExpr)Expr.create(this, Native.mkSeqSuffix(nCtx(), s1.getNativeObject(), s2.getNativeObject())); } /** * Check for sequence containment of s2 in s1. */ public final <R extends Sort> BoolExpr mkContains(Expr<SeqSort<R>> s1, Expr<SeqSort<R>> s2) { checkContextMatch(s1, s2); return (BoolExpr) Expr.create(this, Native.mkSeqContains(nCtx(), s1.getNativeObject(), s2.getNativeObject())); } /** * Check if the string s1 is lexicographically strictly less than s2. */ public BoolExpr MkStringLt(Expr<SeqSort<CharSort>> s1, Expr<SeqSort<CharSort>> s2) { checkContextMatch(s1, s2); return new BoolExpr(this, Native.mkStrLt(nCtx(), s1.getNativeObject(), s2.getNativeObject())); } /** * Check if the string s1 is lexicographically less or equal to s2. */ public BoolExpr MkStringLe(Expr<SeqSort<CharSort>> s1, Expr<SeqSort<CharSort>> s2) { checkContextMatch(s1, s2); return new BoolExpr(this, Native.mkStrLe(nCtx(), s1.getNativeObject(), s2.getNativeObject())); } /** * Retrieve sequence of length one at index. */ public final <R extends Sort> SeqExpr<R> mkAt(Expr<SeqSort<R>> s, Expr<IntSort> index) { checkContextMatch(s, index); return (SeqExpr<R>) Expr.create(this, Native.mkSeqAt(nCtx(), s.getNativeObject(), index.getNativeObject())); } /** * Retrieve element at index. */ public final <R extends Sort> Expr<R> mkNth(Expr<SeqSort<R>> s, Expr<IntSort> index) { checkContextMatch(s, index); return (Expr<R>) Expr.create(this, Native.mkSeqNth(nCtx(), s.getNativeObject(), index.getNativeObject())); } /** * Extract subsequence. */ public final <R extends Sort> SeqExpr<R> mkExtract(Expr<SeqSort<R>> s, Expr<IntSort> offset, Expr<IntSort> length) { checkContextMatch(s, offset, length); return (SeqExpr<R>) Expr.create(this, Native.mkSeqExtract(nCtx(), s.getNativeObject(), offset.getNativeObject(), length.getNativeObject())); } /** * Extract index of sub-string starting at offset. */ public final <R extends Sort> IntExpr mkIndexOf(Expr<SeqSort<R>> s, Expr<SeqSort<R>> substr, Expr<IntSort> offset) { checkContextMatch(s, substr, offset); return (IntExpr)Expr.create(this, Native.mkSeqIndex(nCtx(), s.getNativeObject(), substr.getNativeObject(), offset.getNativeObject())); } /** * Replace the first occurrence of src by dst in s. */ public final <R extends Sort> SeqExpr<R> mkReplace(Expr<SeqSort<R>> s, Expr<SeqSort<R>> src, Expr<SeqSort<R>> dst) { checkContextMatch(s, src, dst); return (SeqExpr<R>) Expr.create(this, Native.mkSeqReplace(nCtx(), s.getNativeObject(), src.getNativeObject(), dst.getNativeObject())); } /** * Convert a regular expression that accepts sequence s. */ public final <R extends Sort> ReExpr<SeqSort<R>> mkToRe(Expr<SeqSort<R>> s) { checkContextMatch(s); return (ReExpr<SeqSort<R>>) Expr.create(this, Native.mkSeqToRe(nCtx(), s.getNativeObject())); } /** * Check for regular expression membership. */ public final <R extends Sort> BoolExpr mkInRe(Expr<SeqSort<R>> s, ReExpr<SeqSort<R>> re) { checkContextMatch(s, re); return (BoolExpr) Expr.create(this, Native.mkSeqInRe(nCtx(), s.getNativeObject(), re.getNativeObject())); } /** * Take the Kleene star of a regular expression. */ public final <R extends Sort> ReExpr<R> mkStar(Expr<ReSort<R>> re) { checkContextMatch(re); return (ReExpr<R>) Expr.create(this, Native.mkReStar(nCtx(), re.getNativeObject())); } /** * Create power regular expression. */ public final <R extends Sort> ReExpr<R> mkPower(Expr<ReSort<R>> re, int n) { return (ReExpr<R>) Expr.create(this, Native.mkRePower(nCtx(), re.getNativeObject(), n)); } /** * Take the lower and upper-bounded Kleene star of a regular expression. */ public final <R extends Sort> ReExpr<R> mkLoop(Expr<ReSort<R>> re, int lo, int hi) { return (ReExpr<R>) Expr.create(this, Native.mkReLoop(nCtx(), re.getNativeObject(), lo, hi)); } /** * Take the lower-bounded Kleene star of a regular expression. */ public final <R extends Sort> ReExpr<R> mkLoop(Expr<ReSort<R>> re, int lo) { return (ReExpr<R>) Expr.create(this, Native.mkReLoop(nCtx(), re.getNativeObject(), lo, 0)); } /** * Take the Kleene plus of a regular expression. */ public final <R extends Sort> ReExpr<R> mkPlus(Expr<ReSort<R>> re) { checkContextMatch(re); return (ReExpr<R>) Expr.create(this, Native.mkRePlus(nCtx(), re.getNativeObject())); } /** * Create the optional regular expression. */ public final <R extends Sort> ReExpr<R> mkOption(Expr<ReSort<R>> re) { checkContextMatch(re); return (ReExpr<R>) Expr.create(this, Native.mkReOption(nCtx(), re.getNativeObject())); } /** * Create the complement regular expression. */ public final <R extends Sort> ReExpr<R> mkComplement(Expr<ReSort<R>> re) { checkContextMatch(re); return (ReExpr<R>) Expr.create(this, Native.mkReComplement(nCtx(), re.getNativeObject())); } /** * Create the concatenation of regular languages. */ @SafeVarargs public final <R extends Sort> ReExpr<R> mkConcat(ReExpr<R>... t) { checkContextMatch(t); return (ReExpr<R>) Expr.create(this, Native.mkReConcat(nCtx(), t.length, AST.arrayToNative(t))); } /** * Create the union of regular languages. */ @SafeVarargs public final <R extends Sort> ReExpr<R> mkUnion(Expr<ReSort<R>>... t) { checkContextMatch(t); return (ReExpr<R>) Expr.create(this, Native.mkReUnion(nCtx(), t.length, AST.arrayToNative(t))); } /** * Create the intersection of regular languages. */ @SafeVarargs public final <R extends Sort> ReExpr<R> mkIntersect(Expr<ReSort<R>>... t) { checkContextMatch(t); return (ReExpr<R>) Expr.create(this, Native.mkReIntersect(nCtx(), t.length, AST.arrayToNative(t))); } /** * Create a difference regular expression. */ public final <R extends Sort> ReExpr<R> mkDiff(Expr<ReSort<R>> a, Expr<ReSort<R>> b) { checkContextMatch(a, b); return (ReExpr<R>) Expr.create(this, Native.mkReDiff(nCtx(), a.getNativeObject(), b.getNativeObject())); } /** * Create the empty regular expression. * Corresponds to re.none */ public final <R extends Sort> ReExpr<R> mkEmptyRe(ReSort<R> s) { return (ReExpr<R>) Expr.create(this, Native.mkReEmpty(nCtx(), s.getNativeObject())); } /** * Create the full regular expression. * Corresponds to re.all */ public final <R extends Sort> ReExpr<R> mkFullRe(ReSort<R> s) { return (ReExpr<R>) Expr.create(this, Native.mkReFull(nCtx(), s.getNativeObject())); } /** * Create regular expression that accepts all characters * R has to be a sequence sort. * Corresponds to re.allchar */ public final <R extends Sort> ReExpr<R> mkAllcharRe(ReSort<R> s) { return (ReExpr<R>) Expr.create(this, Native.mkReAllchar(nCtx(), s.getNativeObject())); } /** * Create a range expression. */ public final ReExpr<SeqSort<CharSort>> mkRange(Expr<SeqSort<CharSort>> lo, Expr<SeqSort<CharSort>> hi) { checkContextMatch(lo, hi); return (ReExpr<SeqSort<CharSort>>) Expr.create(this, Native.mkReRange(nCtx(), lo.getNativeObject(), hi.getNativeObject())); } /** * Create less than or equal to between two characters. */ public BoolExpr mkCharLe(Expr<CharSort> ch1, Expr<CharSort> ch2) { checkContextMatch(ch1, ch2); return (BoolExpr) Expr.create(this, Native.mkCharLe(nCtx(), ch1.getNativeObject(), ch2.getNativeObject())); } /** * Create an integer (code point) from character. */ public IntExpr charToInt(Expr<CharSort> ch) { checkContextMatch(ch); return (IntExpr) Expr.create(this, Native.mkCharToInt(nCtx(), ch.getNativeObject())); } /** * Create a bit-vector (code point) from character. */ public BitVecExpr charToBv(Expr<CharSort> ch) { checkContextMatch(ch); return (BitVecExpr) Expr.create(this, Native.mkCharToBv(nCtx(), ch.getNativeObject())); } /** * Create a character from a bit-vector (code point). */ public Expr<CharSort> charFromBv(BitVecExpr bv) { checkContextMatch(bv); return (Expr<CharSort>) Expr.create(this, Native.mkCharFromBv(nCtx(), bv.getNativeObject())); } /** * Create a check if the character is a digit. */ public BoolExpr mkIsDigit(Expr<CharSort> ch) { checkContextMatch(ch); return (BoolExpr) Expr.create(this, Native.mkCharIsDigit(nCtx(), ch.getNativeObject())); } /** * Create an at-most-k constraint. */ public BoolExpr mkAtMost(Expr<BoolSort>[] args, int k) { checkContextMatch(args); return (BoolExpr) Expr.create(this, Native.mkAtmost(nCtx(), args.length, AST.arrayToNative(args), k)); } /** * Create an at-least-k constraint. */ public BoolExpr mkAtLeast(Expr<BoolSort>[] args, int k) { checkContextMatch(args); return (BoolExpr) Expr.create(this, Native.mkAtleast(nCtx(), args.length, AST.arrayToNative(args), k)); } /** * Create a pseudo-Boolean less-or-equal constraint. */ public BoolExpr mkPBLe(int[] coeffs, Expr<BoolSort>[] args, int k) { checkContextMatch(args); return (BoolExpr) Expr.create(this, Native.mkPble(nCtx(), args.length, AST.arrayToNative(args), coeffs, k)); } /** * Create a pseudo-Boolean greater-or-equal constraint. */ public BoolExpr mkPBGe(int[] coeffs, Expr<BoolSort>[] args, int k) { checkContextMatch(args); return (BoolExpr) Expr.create(this, Native.mkPbge(nCtx(), args.length, AST.arrayToNative(args), coeffs, k)); } /** * Create a pseudo-Boolean equal constraint. */ public BoolExpr mkPBEq(int[] coeffs, Expr<BoolSort>[] args, int k) { checkContextMatch(args); return (BoolExpr) Expr.create(this, Native.mkPbeq(nCtx(), args.length, AST.arrayToNative(args), coeffs, k)); } /** * Create a Term of a given sort. * @param v A string representing the term value in decimal notation. If the given sort is a real, then the * Term can be a rational, that is, a string of the form * {@code [num]* / [num]*}. * @param ty The sort of the * numeral. In the current implementation, the given sort can be an int, * real, or bit-vectors of arbitrary size. * * @return A Term with value {@code v} and sort {@code ty} **/ public final <R extends Sort> Expr<R> mkNumeral(String v, R ty) { checkContextMatch(ty); return (Expr<R>) Expr.create(this, Native.mkNumeral(nCtx(), v, ty.getNativeObject())); } /** * Create a Term of a given sort. This function can be used to create * numerals that fit in a machine integer. It is slightly faster than * {@code MakeNumeral} since it is not necessary to parse a string. * * @param v Value of the numeral * @param ty Sort of the numeral * * @return A Term with value {@code v} and type {@code ty} **/ public final <R extends Sort> Expr<R> mkNumeral(int v, R ty) { checkContextMatch(ty); return (Expr<R>) Expr.create(this, Native.mkInt(nCtx(), v, ty.getNativeObject())); } /** * Create a Term of a given sort. This function can be used to create * numerals that fit in a machine integer. It is slightly faster than * {@code MakeNumeral} since it is not necessary to parse a string. * * @param v Value of the numeral * @param ty Sort of the numeral * * @return A Term with value {@code v} and type {@code ty} **/ public final <R extends Sort> Expr<R> mkNumeral(long v, R ty) { checkContextMatch(ty); return (Expr<R>) Expr.create(this, Native.mkInt64(nCtx(), v, ty.getNativeObject())); } /** * Create a real from a fraction. * @param num numerator of rational. * @param den denominator of rational. * * @return A Term with value {@code num}/{@code den} * and sort Real * @see #mkNumeral(String v, R ty) **/ public RatNum mkReal(int num, int den) { if (den == 0) { throw new Z3Exception("Denominator is zero"); } return new RatNum(this, Native.mkReal(nCtx(), num, den)); } /** * Create a real numeral. * @param v A string representing the Term value in decimal notation. * * @return A Term with value {@code v} and sort Real **/ public RatNum mkReal(String v) { return new RatNum(this, Native.mkNumeral(nCtx(), v, getRealSort() .getNativeObject())); } /** * Create a real numeral. * @param v value of the numeral. * * @return A Term with value {@code v} and sort Real **/ public RatNum mkReal(int v) { return new RatNum(this, Native.mkInt(nCtx(), v, getRealSort() .getNativeObject())); } /** * Create a real numeral. * @param v value of the numeral. * * @return A Term with value {@code v} and sort Real **/ public RatNum mkReal(long v) { return new RatNum(this, Native.mkInt64(nCtx(), v, getRealSort() .getNativeObject())); } /** * Create an integer numeral. * @param v A string representing the Term value in decimal notation. **/ public IntNum mkInt(String v) { return new IntNum(this, Native.mkNumeral(nCtx(), v, getIntSort() .getNativeObject())); } /** * Create an integer numeral. * @param v value of the numeral. * * @return A Term with value {@code v} and sort Integer **/ public IntNum mkInt(int v) { return new IntNum(this, Native.mkInt(nCtx(), v, getIntSort() .getNativeObject())); } /** * Create an integer numeral. * @param v value of the numeral. * * @return A Term with value {@code v} and sort Integer **/ public IntNum mkInt(long v) { return new IntNum(this, Native.mkInt64(nCtx(), v, getIntSort() .getNativeObject())); } /** * Create a bit-vector numeral. * @param v A string representing the value in decimal notation. * @param size the size of the bit-vector **/ public BitVecNum mkBV(String v, int size) { return (BitVecNum) mkNumeral(v, mkBitVecSort(size)); } /** * Create a bit-vector numeral. * @param v value of the numeral. * @param size the size of the bit-vector **/ public BitVecNum mkBV(int v, int size) { return (BitVecNum) mkNumeral(v, mkBitVecSort(size)); } /** * Create a bit-vector numeral. * @param v value of the numeral. * * @param size the size of the bit-vector **/ public BitVecNum mkBV(long v, int size) { return (BitVecNum) mkNumeral(v, mkBitVecSort(size)); } /** * Create a universal Quantifier. * * @param sorts the sorts of the bound variables. * @param names names of the bound variables * @param body the body of the quantifier. * @param weight quantifiers are associated with weights indicating the importance of using the quantifier during instantiation. By default, pass the weight 0. * @param patterns array containing the patterns created using {@code MkPattern}. * @param noPatterns array containing the anti-patterns created using {@code MkPattern}. * @param quantifierID optional symbol to track quantifier. * @param skolemID optional symbol to track skolem constants. * * @return Creates a forall formula, where * {@code weight} is the weight, {@code patterns} is * an array of patterns, {@code sorts} is an array with the sorts * of the bound variables, {@code names} is an array with the * 'names' of the bound variables, and {@code body} is the body * of the quantifier. Quantifiers are associated with weights indicating the * importance of using the quantifier during instantiation. * Note that the bound variables are de-Bruijn indices created using {#mkBound}. * Z3 applies the convention that the last element in {@code names} and * {@code sorts} refers to the variable with index 0, the second to last element * of {@code names} and {@code sorts} refers to the variable * with index 1, etc. **/ public Quantifier mkForall(Sort[] sorts, Symbol[] names, Expr<BoolSort> body, int weight, Pattern[] patterns, Expr<?>[] noPatterns, Symbol quantifierID, Symbol skolemID) { return Quantifier.of(this, true, sorts, names, body, weight, patterns, noPatterns, quantifierID, skolemID); } /** * Creates a universal quantifier using a list of constants that will form the set of bound variables. * @see #mkForall(Sort[],Symbol[],Expr<BoolSort>,int,Pattern[],Expr<?>[],Symbol,Symbol) **/ public Quantifier mkForall(Expr<?>[] boundConstants, Expr<BoolSort> body, int weight, Pattern[] patterns, Expr<?>[] noPatterns, Symbol quantifierID, Symbol skolemID) { return Quantifier.of(this, true, boundConstants, body, weight, patterns, noPatterns, quantifierID, skolemID); } /** * Creates an existential quantifier using de-Bruijn indexed variables. * @see #mkForall(Sort[],Symbol[],Expr<BoolSort>,int,Pattern[],Expr<?>[],Symbol,Symbol) **/ public Quantifier mkExists(Sort[] sorts, Symbol[] names, Expr<BoolSort> body, int weight, Pattern[] patterns, Expr<?>[] noPatterns, Symbol quantifierID, Symbol skolemID) { return Quantifier.of(this, false, sorts, names, body, weight, patterns, noPatterns, quantifierID, skolemID); } /** * Creates an existential quantifier using a list of constants that will form the set of bound variables. * @see #mkForall(Sort[],Symbol[],Expr<BoolSort>,int,Pattern[],Expr<?>[],Symbol,Symbol) **/ public Quantifier mkExists(Expr<?>[] boundConstants, Expr<BoolSort> body, int weight, Pattern[] patterns, Expr<?>[] noPatterns, Symbol quantifierID, Symbol skolemID) { return Quantifier.of(this, false, boundConstants, body, weight, patterns, noPatterns, quantifierID, skolemID); } /** * Create a Quantifier. * @see #mkForall(Sort[],Symbol[],Expr<BoolSort>,int,Pattern[],Expr<?>[],Symbol,Symbol) **/ public Quantifier mkQuantifier(boolean universal, Sort[] sorts, Symbol[] names, Expr<BoolSort> body, int weight, Pattern[] patterns, Expr<?>[] noPatterns, Symbol quantifierID, Symbol skolemID) { if (universal) return mkForall(sorts, names, body, weight, patterns, noPatterns, quantifierID, skolemID); else return mkExists(sorts, names, body, weight, patterns, noPatterns, quantifierID, skolemID); } /** * Create a Quantifier * @see #mkForall(Sort[],Symbol[],Expr<BoolSort>,int,Pattern[],Expr<?>[],Symbol,Symbol) **/ public Quantifier mkQuantifier(boolean universal, Expr<?>[] boundConstants, Expr<BoolSort> body, int weight, Pattern[] patterns, Expr<?>[] noPatterns, Symbol quantifierID, Symbol skolemID) { if (universal) return mkForall(boundConstants, body, weight, patterns, noPatterns, quantifierID, skolemID); else return mkExists(boundConstants, body, weight, patterns, noPatterns, quantifierID, skolemID); } /** * Create a lambda expression. * * {@code sorts} is an array * with the sorts of the bound variables, {@code names} is an array with the * 'names' of the bound variables, and {@code body} is the body of the * lambda. * Note that the bound variables are de-Bruijn indices created using {#mkBound} * Z3 applies the convention that the last element in {@code names} and * {@code sorts} refers to the variable with index 0, the second to last element * of {@code names} and {@code sorts} refers to the variable * with index 1, etc. * * @param sorts the sorts of the bound variables. * @param names names of the bound variables. * @param body the body of the quantifier. **/ public final <R extends Sort> Lambda<R> mkLambda(Sort[] sorts, Symbol[] names, Expr<R> body) { return Lambda.of(this, sorts, names, body); } /** * Create a lambda expression. * * Creates a lambda expression using a list of constants that will * form the set of bound variables. **/ public final <R extends Sort> Lambda<R> mkLambda(Expr<?>[] boundConstants, Expr<R> body) { return Lambda.of(this, boundConstants, body); } /** * Selects the format used for pretty-printing expressions. * Remarks: The * default mode for pretty printing expressions is to produce SMT-LIB style * output where common subexpressions are printed at each occurrence. The * mode is called Z3_PRINT_SMTLIB_FULL. To print shared common * subexpressions only once, use the Z3_PRINT_LOW_LEVEL mode. To print in * way that conforms to SMT-LIB standards and uses let expressions to share * common sub-expressions use Z3_PRINT_SMTLIB_COMPLIANT. * @see AST#toString * @see Pattern#toString * @see FuncDecl#toString * @see Sort#toString **/ public void setPrintMode(Z3_ast_print_mode value) { Native.setAstPrintMode(nCtx(), value.toInt()); } /** * Convert a benchmark into an SMT-LIB formatted string. * @param name Name of the benchmark. The argument is optional. * * @param logic The benchmark logic. * @param status The status string (sat, unsat, or unknown) * @param attributes Other attributes, such as source, difficulty or * category. * @param assumptions Auxiliary assumptions. * @param formula Formula to be checked for consistency in conjunction with assumptions. * * @return A string representation of the benchmark. **/ public String benchmarkToSMTString(String name, String logic, String status, String attributes, Expr<BoolSort>[] assumptions, Expr<BoolSort> formula) { return Native.benchmarkToSmtlibString(nCtx(), name, logic, status, attributes, assumptions.length, AST.arrayToNative(assumptions), formula.getNativeObject()); } /** * Parse the given string using the SMT-LIB2 parser. * * @return A conjunction of assertions. * * If the string contains push/pop commands, the * set of assertions returned are the ones in the * last scope level. **/ public BoolExpr[] parseSMTLIB2String(String str, Symbol[] sortNames, Sort[] sorts, Symbol[] declNames, FuncDecl<?>[] decls) { int csn = Symbol.arrayLength(sortNames); int cs = Sort.arrayLength(sorts); int cdn = Symbol.arrayLength(declNames); int cd = AST.arrayLength(decls); if (csn != cs || cdn != cd) { throw new Z3Exception("Argument size mismatch"); } ASTVector v = new ASTVector(this, Native.parseSmtlib2String(nCtx(), str, AST.arrayLength(sorts), Symbol.arrayToNative(sortNames), AST.arrayToNative(sorts), AST.arrayLength(decls), Symbol.arrayToNative(declNames), AST.arrayToNative(decls))); return v.ToBoolExprArray(); } /** * Parse the given file using the SMT-LIB2 parser. * @see #parseSMTLIB2String **/ public BoolExpr[] parseSMTLIB2File(String fileName, Symbol[] sortNames, Sort[] sorts, Symbol[] declNames, FuncDecl<?>[] decls) { int csn = Symbol.arrayLength(sortNames); int cs = Sort.arrayLength(sorts); int cdn = Symbol.arrayLength(declNames); int cd = AST.arrayLength(decls); if (csn != cs || cdn != cd) throw new Z3Exception("Argument size mismatch"); ASTVector v = new ASTVector(this, Native.parseSmtlib2File(nCtx(), fileName, AST.arrayLength(sorts), Symbol.arrayToNative(sortNames), AST.arrayToNative(sorts), AST.arrayLength(decls), Symbol.arrayToNative(declNames), AST.arrayToNative(decls))); return v.ToBoolExprArray(); } /** * Creates a new Goal. * Remarks: Note that the Context must have been * created with proof generation support if {@code proofs} is set * to true here. * @param models Indicates whether model generation should be enabled. * @param unsatCores Indicates whether unsat core generation should be enabled. * @param proofs Indicates whether proof generation should be * enabled. **/ public Goal mkGoal(boolean models, boolean unsatCores, boolean proofs) { return new Goal(this, models, unsatCores, proofs); } /** * Creates a new ParameterSet. **/ public Params mkParams() { return new Params(this); } /** * The number of supported tactics. **/ public int getNumTactics() { return Native.getNumTactics(nCtx()); } /** * The names of all supported tactics. **/ public String[] getTacticNames() { int n = getNumTactics(); String[] res = new String[n]; for (int i = 0; i < n; i++) res[i] = Native.getTacticName(nCtx(), i); return res; } /** * Returns a string containing a description of the tactic with the given * name. **/ public String getTacticDescription(String name) { return Native.tacticGetDescr(nCtx(), name); } /** * Creates a new Tactic. **/ public Tactic mkTactic(String name) { return new Tactic(this, name); } /** * Create a tactic that applies {@code t1} to a Goal and then * {@code t2} to every subgoal produced by {@code t1} **/ public Tactic andThen(Tactic t1, Tactic t2, Tactic... ts) { checkContextMatch(t1); checkContextMatch(t2); checkContextMatch(ts); long last = 0; if (ts != null && ts.length > 0) { last = ts[ts.length - 1].getNativeObject(); for (int i = ts.length - 2; i >= 0; i--) { last = Native.tacticAndThen(nCtx(), ts[i].getNativeObject(), last); } } if (last != 0) { last = Native.tacticAndThen(nCtx(), t2.getNativeObject(), last); return new Tactic(this, Native.tacticAndThen(nCtx(), t1.getNativeObject(), last)); } else return new Tactic(this, Native.tacticAndThen(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create a tactic that applies {@code t1} to a Goal and then * {@code t2} to every subgoal produced by {@code t1} * * Remarks: Shorthand for {@code AndThen}. **/ public Tactic then(Tactic t1, Tactic t2, Tactic... ts) { return andThen(t1, t2, ts); } /** * Create a tactic that first applies {@code t1} to a Goal and if * it fails then returns the result of {@code t2} applied to the * Goal. **/ public Tactic orElse(Tactic t1, Tactic t2) { checkContextMatch(t1); checkContextMatch(t2); return new Tactic(this, Native.tacticOrElse(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create a tactic that applies {@code t} to a goal for {@code ms} milliseconds. * Remarks: If {@code t} does not * terminate within {@code ms} milliseconds, then it fails. * **/ public Tactic tryFor(Tactic t, int ms) { checkContextMatch(t); return new Tactic(this, Native.tacticTryFor(nCtx(), t.getNativeObject(), ms)); } /** * Create a tactic that applies {@code t} to a given goal if the * probe {@code p} evaluates to true. * Remarks: If {@code p} evaluates to false, then the new tactic behaves like the * {@code skip} tactic. **/ public Tactic when(Probe p, Tactic t) { checkContextMatch(t); checkContextMatch(p); return new Tactic(this, Native.tacticWhen(nCtx(), p.getNativeObject(), t.getNativeObject())); } /** * Create a tactic that applies {@code t1} to a given goal if the * probe {@code p} evaluates to true and {@code t2} * otherwise. **/ public Tactic cond(Probe p, Tactic t1, Tactic t2) { checkContextMatch(p); checkContextMatch(t1); checkContextMatch(t2); return new Tactic(this, Native.tacticCond(nCtx(), p.getNativeObject(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create a tactic that keeps applying {@code t} until the goal * is not modified anymore or the maximum number of iterations {@code max} is reached. **/ public Tactic repeat(Tactic t, int max) { checkContextMatch(t); return new Tactic(this, Native.tacticRepeat(nCtx(), t.getNativeObject(), max)); } /** * Create a tactic that just returns the given goal. **/ public Tactic skip() { return new Tactic(this, Native.tacticSkip(nCtx())); } /** * Create a tactic always fails. **/ public Tactic fail() { return new Tactic(this, Native.tacticFail(nCtx())); } /** * Create a tactic that fails if the probe {@code p} evaluates to * false. **/ public Tactic failIf(Probe p) { checkContextMatch(p); return new Tactic(this, Native.tacticFailIf(nCtx(), p.getNativeObject())); } /** * Create a tactic that fails if the goal is not trivially satisfiable (i.e., * empty) or trivially unsatisfiable (i.e., contains `false'). **/ public Tactic failIfNotDecided() { return new Tactic(this, Native.tacticFailIfNotDecided(nCtx())); } /** * Create a tactic that applies {@code t} using the given set of * parameters {@code p}. **/ public Tactic usingParams(Tactic t, Params p) { checkContextMatch(t); checkContextMatch(p); return new Tactic(this, Native.tacticUsingParams(nCtx(), t.getNativeObject(), p.getNativeObject())); } /** * Create a tactic that applies {@code t} using the given set of * parameters {@code p}. * Remarks: Alias for * {@code UsingParams} **/ public Tactic with(Tactic t, Params p) { return usingParams(t, p); } /** * Create a tactic that applies the given tactics in parallel until one of them succeeds (i.e., the first that doesn't fail). **/ public Tactic parOr(Tactic... t) { checkContextMatch(t); return new Tactic(this, Native.tacticParOr(nCtx(), Tactic.arrayLength(t), Tactic.arrayToNative(t))); } /** * Create a tactic that applies {@code t1} to a given goal and * then {@code t2} to every subgoal produced by {@code t1}. The subgoals are processed in parallel. **/ public Tactic parAndThen(Tactic t1, Tactic t2) { checkContextMatch(t1); checkContextMatch(t2); return new Tactic(this, Native.tacticParAndThen(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Interrupt the execution of a Z3 procedure. * Remarks: This procedure can be * used to interrupt: solvers, simplifiers and tactics. **/ public void interrupt() { Native.interrupt(nCtx()); } /** * The number of supported simplifiers. **/ public int getNumSimplifiers() { return Native.getNumSimplifiers(nCtx()); } /** * The names of all supported simplifiers. **/ public String[] getSimplifierNames() { int n = getNumSimplifiers(); String[] res = new String[n]; for (int i = 0; i < n; i++) res[i] = Native.getSimplifierName(nCtx(), i); return res; } /** * Returns a string containing a description of the simplifier with the given * name. **/ public String getSimplifierDescription(String name) { return Native.simplifierGetDescr(nCtx(), name); } /** * Creates a new Simplifier. **/ public Simplifier mkSimplifier(String name) { return new Simplifier(this, name); } /** * Create a simplifier that applies {@code t1} and then {@code t1} **/ public Simplifier andThen(Simplifier t1, Simplifier t2, Simplifier... ts) { checkContextMatch(t1); checkContextMatch(t2); checkContextMatch(ts); long last = 0; if (ts != null && ts.length > 0) { last = ts[ts.length - 1].getNativeObject(); for (int i = ts.length - 2; i >= 0; i--) { last = Native.simplifierAndThen(nCtx(), ts[i].getNativeObject(), last); } } if (last != 0) { last = Native.simplifierAndThen(nCtx(), t2.getNativeObject(), last); return new Simplifier(this, Native.simplifierAndThen(nCtx(), t1.getNativeObject(), last)); } else return new Simplifier(this, Native.simplifierAndThen(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Create a simplifier that applies {@code t1} and then {@code t2} * * Remarks: Shorthand for {@code AndThen}. **/ public Simplifier then(Simplifier t1, Simplifier t2, Simplifier... ts) { return andThen(t1, t2, ts); } /** * Create a simplifier that applies {@code t} using the given set of * parameters {@code p}. **/ public Simplifier usingParams(Simplifier t, Params p) { checkContextMatch(t); checkContextMatch(p); return new Simplifier(this, Native.simplifierUsingParams(nCtx(), t.getNativeObject(), p.getNativeObject())); } /** * Create a simplifier that applies {@code t} using the given set of * parameters {@code p}. * Remarks: Alias for * {@code UsingParams} **/ public Simplifier with(Simplifier t, Params p) { return usingParams(t, p); } /** * The number of supported Probes. **/ public int getNumProbes() { return Native.getNumProbes(nCtx()); } /** * The names of all supported Probes. **/ public String[] getProbeNames() { int n = getNumProbes(); String[] res = new String[n]; for (int i = 0; i < n; i++) res[i] = Native.getProbeName(nCtx(), i); return res; } /** * Returns a string containing a description of the probe with the given * name. **/ public String getProbeDescription(String name) { return Native.probeGetDescr(nCtx(), name); } /** * Creates a new Probe. **/ public Probe mkProbe(String name) { return new Probe(this, name); } /** * Create a probe that always evaluates to {@code val}. **/ public Probe constProbe(double val) { return new Probe(this, Native.probeConst(nCtx(), val)); } /** * Create a probe that evaluates to {@code true} when the value returned by * {@code p1} is less than the value returned by {@code p2} **/ public Probe lt(Probe p1, Probe p2) { checkContextMatch(p1); checkContextMatch(p2); return new Probe(this, Native.probeLt(nCtx(), p1.getNativeObject(), p2.getNativeObject())); } /** * Create a probe that evaluates to {@code true} when the value returned by * {@code p1} is greater than the value returned by {@code p2} **/ public Probe gt(Probe p1, Probe p2) { checkContextMatch(p1); checkContextMatch(p2); return new Probe(this, Native.probeGt(nCtx(), p1.getNativeObject(), p2.getNativeObject())); } /** * Create a probe that evaluates to {@code true} when the value returned by * {@code p1} is less than or equal the value returned by * {@code p2} **/ public Probe le(Probe p1, Probe p2) { checkContextMatch(p1); checkContextMatch(p2); return new Probe(this, Native.probeLe(nCtx(), p1.getNativeObject(), p2.getNativeObject())); } /** * Create a probe that evaluates to {@code true} when the value returned by * {@code p1} is greater than or equal the value returned by * {@code p2} **/ public Probe ge(Probe p1, Probe p2) { checkContextMatch(p1); checkContextMatch(p2); return new Probe(this, Native.probeGe(nCtx(), p1.getNativeObject(), p2.getNativeObject())); } /** * Create a probe that evaluates to {@code true} when the value returned by * {@code p1} is equal to the value returned by {@code p2} **/ public Probe eq(Probe p1, Probe p2) { checkContextMatch(p1); checkContextMatch(p2); return new Probe(this, Native.probeEq(nCtx(), p1.getNativeObject(), p2.getNativeObject())); } /** * Create a probe that evaluates to {@code true} when the value {@code p1} and {@code p2} evaluate to {@code true}. **/ public Probe and(Probe p1, Probe p2) { checkContextMatch(p1); checkContextMatch(p2); return new Probe(this, Native.probeAnd(nCtx(), p1.getNativeObject(), p2.getNativeObject())); } /** * Create a probe that evaluates to {@code true} when the value {@code p1} or {@code p2} evaluate to {@code true}. **/ public Probe or(Probe p1, Probe p2) { checkContextMatch(p1); checkContextMatch(p2); return new Probe(this, Native.probeOr(nCtx(), p1.getNativeObject(), p2.getNativeObject())); } /** * Create a probe that evaluates to {@code true} when the value {@code p} does not evaluate to {@code true}. **/ public Probe not(Probe p) { checkContextMatch(p); return new Probe(this, Native.probeNot(nCtx(), p.getNativeObject())); } /** * Creates a new (incremental) solver. * Remarks: This solver also uses a set * of builtin tactics for handling the first check-sat command, and * check-sat commands that take more than a given number of milliseconds to * be solved. **/ public Solver mkSolver() { return mkSolver((Symbol) null); } /** * Creates a new (incremental) solver. * Remarks: This solver also uses a set * of builtin tactics for handling the first check-sat command, and * check-sat commands that take more than a given number of milliseconds to * be solved. **/ public Solver mkSolver(Symbol logic) { if (logic == null) return new Solver(this, Native.mkSolver(nCtx())); else return new Solver(this, Native.mkSolverForLogic(nCtx(), logic.getNativeObject())); } /** * Creates a new (incremental) solver. * @see #mkSolver(Symbol) **/ public Solver mkSolver(String logic) { return mkSolver(mkSymbol(logic)); } /** * Creates a new (incremental) solver. **/ public Solver mkSimpleSolver() { return new Solver(this, Native.mkSimpleSolver(nCtx())); } /** * Creates a solver that is implemented using the given tactic. * Remarks: * The solver supports the commands {@code Push} and {@code Pop}, * but it will always solve each check from scratch. **/ public Solver mkSolver(Tactic t) { return new Solver(this, Native.mkSolverFromTactic(nCtx(), t.getNativeObject())); } /** * Creates a solver that is uses the simplifier pre-processing. **/ public Solver mkSolver(Solver s, Simplifier simp) { return new Solver(this, Native.solverAddSimplifier(nCtx(), s.getNativeObject(), simp.getNativeObject())); } /** * Create a Fixedpoint context. **/ public Fixedpoint mkFixedpoint() { return new Fixedpoint(this); } /** * Create a Optimize context. **/ public Optimize mkOptimize() { return new Optimize(this); } /** * Create the floating-point RoundingMode sort. * @throws Z3Exception **/ public FPRMSort mkFPRoundingModeSort() { return new FPRMSort(this); } /** * Create a numeral of RoundingMode sort which represents the NearestTiesToEven rounding mode. * @throws Z3Exception **/ public FPRMExpr mkFPRoundNearestTiesToEven() { return new FPRMExpr(this, Native.mkFpaRoundNearestTiesToEven(nCtx())); } /** * Create a numeral of RoundingMode sort which represents the NearestTiesToEven rounding mode. * @throws Z3Exception **/ public FPRMNum mkFPRNE() { return new FPRMNum(this, Native.mkFpaRne(nCtx())); } /** * Create a numeral of RoundingMode sort which represents the NearestTiesToAway rounding mode. * @throws Z3Exception **/ public FPRMNum mkFPRoundNearestTiesToAway() { return new FPRMNum(this, Native.mkFpaRoundNearestTiesToAway(nCtx())); } /** * Create a numeral of RoundingMode sort which represents the NearestTiesToAway rounding mode. * @throws Z3Exception **/ public FPRMNum mkFPRNA() { return new FPRMNum(this, Native.mkFpaRna(nCtx())); } /** * Create a numeral of RoundingMode sort which represents the RoundTowardPositive rounding mode. * @throws Z3Exception **/ public FPRMNum mkFPRoundTowardPositive() { return new FPRMNum(this, Native.mkFpaRoundTowardPositive(nCtx())); } /** * Create a numeral of RoundingMode sort which represents the RoundTowardPositive rounding mode. * @throws Z3Exception **/ public FPRMNum mkFPRTP() { return new FPRMNum(this, Native.mkFpaRtp(nCtx())); } /** * Create a numeral of RoundingMode sort which represents the RoundTowardNegative rounding mode. * @throws Z3Exception **/ public FPRMNum mkFPRoundTowardNegative() { return new FPRMNum(this, Native.mkFpaRoundTowardNegative(nCtx())); } /** * Create a numeral of RoundingMode sort which represents the RoundTowardNegative rounding mode. * @throws Z3Exception **/ public FPRMNum mkFPRTN() { return new FPRMNum(this, Native.mkFpaRtn(nCtx())); } /** * Create a numeral of RoundingMode sort which represents the RoundTowardZero rounding mode. * @throws Z3Exception **/ public FPRMNum mkFPRoundTowardZero() { return new FPRMNum(this, Native.mkFpaRoundTowardZero(nCtx())); } /** * Create a numeral of RoundingMode sort which represents the RoundTowardZero rounding mode. * @throws Z3Exception **/ public FPRMNum mkFPRTZ() { return new FPRMNum(this, Native.mkFpaRtz(nCtx())); } /** * Create a FloatingPoint sort. * @param ebits exponent bits in the FloatingPoint sort. * @param sbits significand bits in the FloatingPoint sort. * @throws Z3Exception **/ public FPSort mkFPSort(int ebits, int sbits) { return new FPSort(this, ebits, sbits); } /** * Create the half-precision (16-bit) FloatingPoint sort. * @throws Z3Exception **/ public FPSort mkFPSortHalf() { return new FPSort(this, Native.mkFpaSortHalf(nCtx())); } /** * Create the half-precision (16-bit) FloatingPoint sort. * @throws Z3Exception **/ public FPSort mkFPSort16() { return new FPSort(this, Native.mkFpaSort16(nCtx())); } /** * Create the single-precision (32-bit) FloatingPoint sort. * @throws Z3Exception **/ public FPSort mkFPSortSingle() { return new FPSort(this, Native.mkFpaSortSingle(nCtx())); } /** * Create the single-precision (32-bit) FloatingPoint sort. * @throws Z3Exception **/ public FPSort mkFPSort32() { return new FPSort(this, Native.mkFpaSort32(nCtx())); } /** * Create the double-precision (64-bit) FloatingPoint sort. * @throws Z3Exception **/ public FPSort mkFPSortDouble() { return new FPSort(this, Native.mkFpaSortDouble(nCtx())); } /** * Create the double-precision (64-bit) FloatingPoint sort. * @throws Z3Exception **/ public FPSort mkFPSort64() { return new FPSort(this, Native.mkFpaSort64(nCtx())); } /** * Create the quadruple-precision (128-bit) FloatingPoint sort. * @throws Z3Exception **/ public FPSort mkFPSortQuadruple() { return new FPSort(this, Native.mkFpaSortQuadruple(nCtx())); } /** * Create the quadruple-precision (128-bit) FloatingPoint sort. * @throws Z3Exception **/ public FPSort mkFPSort128() { return new FPSort(this, Native.mkFpaSort128(nCtx())); } /** * Create a NaN of sort s. * @param s FloatingPoint sort. * @throws Z3Exception **/ public FPNum mkFPNaN(FPSort s) { return new FPNum(this, Native.mkFpaNan(nCtx(), s.getNativeObject())); } /** * Create a floating-point infinity of sort s. * @param s FloatingPoint sort. * @param negative indicates whether the result should be negative. * @throws Z3Exception **/ public FPNum mkFPInf(FPSort s, boolean negative) { return new FPNum(this, Native.mkFpaInf(nCtx(), s.getNativeObject(), negative)); } /** * Create a floating-point zero of sort s. * @param s FloatingPoint sort. * @param negative indicates whether the result should be negative. * @throws Z3Exception **/ public FPNum mkFPZero(FPSort s, boolean negative) { return new FPNum(this, Native.mkFpaZero(nCtx(), s.getNativeObject(), negative)); } /** * Create a numeral of FloatingPoint sort from a float. * @param v numeral value. * @param s FloatingPoint sort. * @throws Z3Exception **/ public FPNum mkFPNumeral(float v, FPSort s) { return new FPNum(this, Native.mkFpaNumeralFloat(nCtx(), v, s.getNativeObject())); } /** * Create a numeral of FloatingPoint sort from a double. * @param v numeral value. * @param s FloatingPoint sort. * @throws Z3Exception **/ public FPNum mkFPNumeral(double v, FPSort s) { return new FPNum(this, Native.mkFpaNumeralDouble(nCtx(), v, s.getNativeObject())); } /** * Create a numeral of FloatingPoint sort from an int. * @param v numeral value. * @param s FloatingPoint sort. * @throws Z3Exception **/ public FPNum mkFPNumeral(int v, FPSort s) { return new FPNum(this, Native.mkFpaNumeralInt(nCtx(), v, s.getNativeObject())); } /** * Create a numeral of FloatingPoint sort from a sign bit and two integers. * @param sgn the sign. * @param exp the exponent. * @param sig the significand. * @param s FloatingPoint sort. * @throws Z3Exception **/ public FPNum mkFPNumeral(boolean sgn, int exp, int sig, FPSort s) { return new FPNum(this, Native.mkFpaNumeralIntUint(nCtx(), sgn, exp, sig, s.getNativeObject())); } /** * Create a numeral of FloatingPoint sort from a sign bit and two 64-bit integers. * @param sgn the sign. * @param exp the exponent. * @param sig the significand. * @param s FloatingPoint sort. * @throws Z3Exception **/ public FPNum mkFPNumeral(boolean sgn, long exp, long sig, FPSort s) { return new FPNum(this, Native.mkFpaNumeralInt64Uint64(nCtx(), sgn, exp, sig, s.getNativeObject())); } /** * Create a numeral of FloatingPoint sort from a float. * @param v numeral value. * @param s FloatingPoint sort. * @throws Z3Exception **/ public FPNum mkFP(float v, FPSort s) { return mkFPNumeral(v, s); } /** * Create a numeral of FloatingPoint sort from a double. * @param v numeral value. * @param s FloatingPoint sort. * @throws Z3Exception **/ public FPNum mkFP(double v, FPSort s) { return mkFPNumeral(v, s); } /** * Create a numeral of FloatingPoint sort from an int. * @param v numeral value. * @param s FloatingPoint sort. * @throws Z3Exception **/ public FPNum mkFP(int v, FPSort s) { return mkFPNumeral(v, s); } /** * Create a numeral of FloatingPoint sort from a sign bit and two integers. * @param sgn the sign. * @param exp the exponent. * @param sig the significand. * @param s FloatingPoint sort. * @throws Z3Exception **/ public FPNum mkFP(boolean sgn, int exp, int sig, FPSort s) { return mkFPNumeral(sgn, exp, sig, s); } /** * Create a numeral of FloatingPoint sort from a sign bit and two 64-bit integers. * @param sgn the sign. * @param exp the exponent. * @param sig the significand. * @param s FloatingPoint sort. * @throws Z3Exception **/ public FPNum mkFP(boolean sgn, long exp, long sig, FPSort s) { return mkFPNumeral(sgn, exp, sig, s); } /** * Floating-point absolute value * @param t floating-point term * @throws Z3Exception **/ public FPExpr mkFPAbs(Expr<FPSort> t) { return new FPExpr(this, Native.mkFpaAbs(nCtx(), t.getNativeObject())); } /** * Floating-point negation * @param t floating-point term * @throws Z3Exception **/ public FPExpr mkFPNeg(Expr<FPSort> t) { return new FPExpr(this, Native.mkFpaNeg(nCtx(), t.getNativeObject())); } /** * Floating-point addition * @param rm rounding mode term * @param t1 floating-point term * @param t2 floating-point term * @throws Z3Exception **/ public FPExpr mkFPAdd(Expr<FPRMSort> rm, Expr<FPSort> t1, Expr<FPSort> t2) { return new FPExpr(this, Native.mkFpaAdd(nCtx(), rm.getNativeObject(), t1.getNativeObject(), t2.getNativeObject())); } /** * Floating-point subtraction * @param rm rounding mode term * @param t1 floating-point term * @param t2 floating-point term * @throws Z3Exception **/ public FPExpr mkFPSub(Expr<FPRMSort> rm, Expr<FPSort> t1, Expr<FPSort> t2) { return new FPExpr(this, Native.mkFpaSub(nCtx(), rm.getNativeObject(), t1.getNativeObject(), t2.getNativeObject())); } /** * Floating-point multiplication * @param rm rounding mode term * @param t1 floating-point term * @param t2 floating-point term * @throws Z3Exception **/ public FPExpr mkFPMul(Expr<FPRMSort> rm, Expr<FPSort> t1, Expr<FPSort> t2) { return new FPExpr(this, Native.mkFpaMul(nCtx(), rm.getNativeObject(), t1.getNativeObject(), t2.getNativeObject())); } /** * Floating-point division * @param rm rounding mode term * @param t1 floating-point term * @param t2 floating-point term * @throws Z3Exception **/ public FPExpr mkFPDiv(Expr<FPRMSort> rm, Expr<FPSort> t1, Expr<FPSort> t2) { return new FPExpr(this, Native.mkFpaDiv(nCtx(), rm.getNativeObject(), t1.getNativeObject(), t2.getNativeObject())); } /** * Floating-point fused multiply-add * @param rm rounding mode term * @param t1 floating-point term * @param t2 floating-point term * @param t3 floating-point term * Remarks: * The result is round((t1 * t2) + t3) * @throws Z3Exception **/ public FPExpr mkFPFMA(Expr<FPRMSort> rm, Expr<FPSort> t1, Expr<FPSort> t2, Expr<FPSort> t3) { return new FPExpr(this, Native.mkFpaFma(nCtx(), rm.getNativeObject(), t1.getNativeObject(), t2.getNativeObject(), t3.getNativeObject())); } /** * Floating-point square root * @param rm rounding mode term * @param t floating-point term * @throws Z3Exception **/ public FPExpr mkFPSqrt(Expr<FPRMSort> rm, Expr<FPSort> t) { return new FPExpr(this, Native.mkFpaSqrt(nCtx(), rm.getNativeObject(), t.getNativeObject())); } /** * Floating-point remainder * @param t1 floating-point term * @param t2 floating-point term * @throws Z3Exception **/ public FPExpr mkFPRem(Expr<FPSort> t1, Expr<FPSort> t2) { return new FPExpr(this, Native.mkFpaRem(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Floating-point roundToIntegral. Rounds a floating-point number to * the closest integer, again represented as a floating-point number. * @param rm term of RoundingMode sort * @param t floating-point term * @throws Z3Exception **/ public FPExpr mkFPRoundToIntegral(Expr<FPRMSort> rm, Expr<FPSort> t) { return new FPExpr(this, Native.mkFpaRoundToIntegral(nCtx(), rm.getNativeObject(), t.getNativeObject())); } /** * Minimum of floating-point numbers. * @param t1 floating-point term * @param t2 floating-point term * @throws Z3Exception **/ public FPExpr mkFPMin(Expr<FPSort> t1, Expr<FPSort> t2) { return new FPExpr(this, Native.mkFpaMin(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Maximum of floating-point numbers. * @param t1 floating-point term * @param t2 floating-point term * @throws Z3Exception **/ public FPExpr mkFPMax(Expr<FPSort> t1, Expr<FPSort> t2) { return new FPExpr(this, Native.mkFpaMax(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Floating-point less than or equal. * @param t1 floating-point term * @param t2 floating-point term * @throws Z3Exception **/ public BoolExpr mkFPLEq(Expr<FPSort> t1, Expr<FPSort> t2) { return new BoolExpr(this, Native.mkFpaLeq(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Floating-point less than. * @param t1 floating-point term * @param t2 floating-point term * @throws Z3Exception **/ public BoolExpr mkFPLt(Expr<FPSort> t1, Expr<FPSort> t2) { return new BoolExpr(this, Native.mkFpaLt(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Floating-point greater than or equal. * @param t1 floating-point term * @param t2 floating-point term * @throws Z3Exception **/ public BoolExpr mkFPGEq(Expr<FPSort> t1, Expr<FPSort> t2) { return new BoolExpr(this, Native.mkFpaGeq(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Floating-point greater than. * @param t1 floating-point term * @param t2 floating-point term * @throws Z3Exception **/ public BoolExpr mkFPGt(Expr<FPSort> t1, Expr<FPSort> t2) { return new BoolExpr(this, Native.mkFpaGt(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Floating-point equality. * @param t1 floating-point term * @param t2 floating-point term * Remarks: * Note that this is IEEE 754 equality (as opposed to standard =). * @throws Z3Exception **/ public BoolExpr mkFPEq(Expr<FPSort> t1, Expr<FPSort> t2) { return new BoolExpr(this, Native.mkFpaEq(nCtx(), t1.getNativeObject(), t2.getNativeObject())); } /** * Predicate indicating whether t is a normal floating-point number.\ * @param t floating-point term * @throws Z3Exception **/ public BoolExpr mkFPIsNormal(Expr<FPSort> t) { return new BoolExpr(this, Native.mkFpaIsNormal(nCtx(), t.getNativeObject())); } /** * Predicate indicating whether t is a subnormal floating-point number.\ * @param t floating-point term * @throws Z3Exception **/ public BoolExpr mkFPIsSubnormal(Expr<FPSort> t) { return new BoolExpr(this, Native.mkFpaIsSubnormal(nCtx(), t.getNativeObject())); } /** * Predicate indicating whether t is a floating-point number with zero value, i.e., +0 or -0. * @param t floating-point term * @throws Z3Exception **/ public BoolExpr mkFPIsZero(Expr<FPSort> t) { return new BoolExpr(this, Native.mkFpaIsZero(nCtx(), t.getNativeObject())); } /** * Predicate indicating whether t is a floating-point number representing +oo or -oo. * @param t floating-point term * @throws Z3Exception **/ public BoolExpr mkFPIsInfinite(Expr<FPSort> t) { return new BoolExpr(this, Native.mkFpaIsInfinite(nCtx(), t.getNativeObject())); } /** * Predicate indicating whether t is a NaN. * @param t floating-point term * @throws Z3Exception **/ public BoolExpr mkFPIsNaN(Expr<FPSort> t) { return new BoolExpr(this, Native.mkFpaIsNan(nCtx(), t.getNativeObject())); } /** * Predicate indicating whether t is a negative floating-point number. * @param t floating-point term * @throws Z3Exception **/ public BoolExpr mkFPIsNegative(Expr<FPSort> t) { return new BoolExpr(this, Native.mkFpaIsNegative(nCtx(), t.getNativeObject())); } /** * Predicate indicating whether t is a positive floating-point number. * @param t floating-point term * @throws Z3Exception **/ public BoolExpr mkFPIsPositive(Expr<FPSort> t) { return new BoolExpr(this, Native.mkFpaIsPositive(nCtx(), t.getNativeObject())); } /** * Create an expression of FloatingPoint sort from three bit-vector expressions. * @param sgn bit-vector term (of size 1) representing the sign. * @param sig bit-vector term representing the significand. * @param exp bit-vector term representing the exponent. * Remarks: * This is the operator named `fp' in the SMT FP theory definition. * Note that sgn is required to be a bit-vector of size 1. Significand and exponent * are required to be greater than 1 and 2 respectively. The FloatingPoint sort * of the resulting expression is automatically determined from the bit-vector sizes * of the arguments. * @throws Z3Exception **/ public FPExpr mkFP(Expr<BitVecSort> sgn, Expr<BitVecSort> sig, Expr<BitVecSort> exp) { return new FPExpr(this, Native.mkFpaFp(nCtx(), sgn.getNativeObject(), sig.getNativeObject(), exp.getNativeObject())); } /** * Conversion of a single IEEE 754-2008 bit-vector into a floating-point number. * @param bv bit-vector value (of size m). * @param s FloatingPoint sort (ebits+sbits == m) * Remarks: * Produces a term that represents the conversion of a bit-vector term bv to a * floating-point term of sort s. The bit-vector size of bv (m) must be equal * to ebits+sbits of s. The format of the bit-vector is as defined by the * IEEE 754-2008 interchange format. * @throws Z3Exception **/ public FPExpr mkFPToFP(Expr<BitVecSort> bv, FPSort s) { return new FPExpr(this, Native.mkFpaToFpBv(nCtx(), bv.getNativeObject(), s.getNativeObject())); } /** * Conversion of a FloatingPoint term into another term of different FloatingPoint sort. * @param rm RoundingMode term. * @param t FloatingPoint term. * @param s FloatingPoint sort. * Remarks: * Produces a term that represents the conversion of a floating-point term t to a * floating-point term of sort s. If necessary, the result will be rounded according * to rounding mode rm. * @throws Z3Exception **/ public FPExpr mkFPToFP(Expr<FPRMSort> rm, FPExpr t, FPSort s) { return new FPExpr(this, Native.mkFpaToFpFloat(nCtx(), rm.getNativeObject(), t.getNativeObject(), s.getNativeObject())); } /** * Conversion of a term of real sort into a term of FloatingPoint sort. * @param rm RoundingMode term. * @param t term of Real sort. * @param s FloatingPoint sort. * Remarks: * Produces a term that represents the conversion of term t of real sort into a * floating-point term of sort s. If necessary, the result will be rounded according * to rounding mode rm. * @throws Z3Exception **/ public FPExpr mkFPToFP(Expr<FPRMSort> rm, RealExpr t, FPSort s) { return new FPExpr(this, Native.mkFpaToFpReal(nCtx(), rm.getNativeObject(), t.getNativeObject(), s.getNativeObject())); } /** * Conversion of a 2's complement signed bit-vector term into a term of FloatingPoint sort. * @param rm RoundingMode term. * @param t term of bit-vector sort. * @param s FloatingPoint sort. * @param signed flag indicating whether t is interpreted as signed or unsigned bit-vector. * Remarks: * Produces a term that represents the conversion of the bit-vector term t into a * floating-point term of sort s. The bit-vector t is taken to be in signed * 2's complement format (when signed==true, otherwise unsigned). If necessary, the * result will be rounded according to rounding mode rm. * @throws Z3Exception **/ public FPExpr mkFPToFP(Expr<FPRMSort> rm, Expr<BitVecSort> t, FPSort s, boolean signed) { if (signed) return new FPExpr(this, Native.mkFpaToFpSigned(nCtx(), rm.getNativeObject(), t.getNativeObject(), s.getNativeObject())); else return new FPExpr(this, Native.mkFpaToFpUnsigned(nCtx(), rm.getNativeObject(), t.getNativeObject(), s.getNativeObject())); } /** * Conversion of a floating-point number to another FloatingPoint sort s. * @param s FloatingPoint sort * @param rm floating-point rounding mode term * @param t floating-point term * Remarks: * Produces a term that represents the conversion of a floating-point term t to a different * FloatingPoint sort s. If necessary, rounding according to rm is applied. * @throws Z3Exception **/ public FPExpr mkFPToFP(FPSort s, Expr<FPRMSort> rm, Expr<FPSort> t) { return new FPExpr(this, Native.mkFpaToFpFloat(nCtx(), s.getNativeObject(), rm.getNativeObject(), t.getNativeObject())); } /** * Conversion of a floating-point term into a bit-vector. * @param rm RoundingMode term. * @param t FloatingPoint term * @param sz Size of the resulting bit-vector. * @param signed Indicates whether the result is a signed or unsigned bit-vector. * Remarks: * Produces a term that represents the conversion of the floating-point term t into a * bit-vector term of size sz in 2's complement format (signed when signed==true). If necessary, * the result will be rounded according to rounding mode rm. * @throws Z3Exception **/ public BitVecExpr mkFPToBV(Expr<FPRMSort> rm, Expr<FPSort> t, int sz, boolean signed) { if (signed) return new BitVecExpr(this, Native.mkFpaToSbv(nCtx(), rm.getNativeObject(), t.getNativeObject(), sz)); else return new BitVecExpr(this, Native.mkFpaToUbv(nCtx(), rm.getNativeObject(), t.getNativeObject(), sz)); } /** * Conversion of a floating-point term into a real-numbered term. * @param t FloatingPoint term * Remarks: * Produces a term that represents the conversion of the floating-point term t into a * real number. Note that this type of conversion will often result in non-linear * constraints over real terms. * @throws Z3Exception **/ public RealExpr mkFPToReal(Expr<FPSort> t) { return new RealExpr(this, Native.mkFpaToReal(nCtx(), t.getNativeObject())); } /** * Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format. * @param t FloatingPoint term. * Remarks: * The size of the resulting bit-vector is automatically determined. Note that * IEEE 754-2008 allows multiple different representations of NaN. This conversion * knows only one NaN and it will always produce the same bit-vector representation of * that NaN. * @throws Z3Exception **/ public BitVecExpr mkFPToIEEEBV(Expr<FPSort> t) { return new BitVecExpr(this, Native.mkFpaToIeeeBv(nCtx(), t.getNativeObject())); } /** * Conversion of a real-sorted significand and an integer-sorted exponent into a term of FloatingPoint sort. * @param rm RoundingMode term. * @param exp Exponent term of Int sort. * @param sig Significand term of Real sort. * @param s FloatingPoint sort. * Remarks: * Produces a term that represents the conversion of sig * 2^exp into a * floating-point term of sort s. If necessary, the result will be rounded * according to rounding mode rm. * @throws Z3Exception **/ public BitVecExpr mkFPToFP(Expr<FPRMSort> rm, Expr<IntSort> exp, Expr<RealSort> sig, FPSort s) { return new BitVecExpr(this, Native.mkFpaToFpIntReal(nCtx(), rm.getNativeObject(), exp.getNativeObject(), sig.getNativeObject(), s.getNativeObject())); } /** * Creates or a linear order. * @param index The index of the order. * @param sort The sort of the order. */ public final <R extends Sort> FuncDecl<BoolSort> mkLinearOrder(R sort, int index) { return (FuncDecl<BoolSort>) FuncDecl.create( this, Native.mkLinearOrder( nCtx(), sort.getNativeObject(), index ) ); } /** * Creates or a partial order. * @param index The index of the order. * @param sort The sort of the order. */ public final <R extends Sort> FuncDecl<BoolSort> mkPartialOrder(R sort, int index) { return (FuncDecl<BoolSort>) FuncDecl.create( this, Native.mkPartialOrder( nCtx(), sort.getNativeObject(), index ) ); } /** * Wraps an AST. * Remarks: This function is used for transitions between * native and managed objects. Note that {@code nativeObject} * must be a native object obtained from Z3 (e.g., through * {@code UnwrapAST}) and that it must have a correct reference count. * @see Native#incRef * @see #unwrapAST * @param nativeObject The native pointer to wrap. **/ public AST wrapAST(long nativeObject) { return AST.create(this, nativeObject); } /** * Unwraps an AST. * Remarks: This function is used for transitions between * native and managed objects. It returns the native pointer to the AST. * Note that AST objects are reference counted and unwrapping an AST * disables automatic reference counting, i.e., all references to the IntPtr * that is returned must be handled externally and through native calls (see * e.g., * @see Native#incRef * @see #wrapAST * @param a The AST to unwrap. **/ public long unwrapAST(AST a) { return a.getNativeObject(); } /** * Return a string describing all available parameters to * {@code Expr.Simplify}. **/ public String SimplifyHelp() { return Native.simplifyGetHelp(nCtx()); } /** * Retrieves parameter descriptions for simplifier. **/ public ParamDescrs getSimplifyParameterDescriptions() { return new ParamDescrs(this, Native.simplifyGetParamDescrs(nCtx())); } /** * Update a mutable configuration parameter. * Remarks: The list of all * configuration parameters can be obtained using the Z3 executable: * {@code z3.exe -ini?} Only a few configuration parameters are mutable * once the context is created. An exception is thrown when trying to modify * an immutable parameter. **/ public void updateParamValue(String id, String value) { Native.updateParamValue(nCtx(), id, value); } public long nCtx() { if (m_ctx == 0) throw new Z3Exception("Context closed"); return m_ctx; } void checkContextMatch(Z3Object other) { if (this != other.getContext()) throw new Z3Exception("Context mismatch"); } void checkContextMatch(Z3Object other1, Z3Object other2) { checkContextMatch(other1); checkContextMatch(other2); } void checkContextMatch(Z3Object other1, Z3Object other2, Z3Object other3) { checkContextMatch(other1); checkContextMatch(other2); checkContextMatch(other3); } void checkContextMatch(Z3Object[] arr) { if (arr != null) for (Z3Object a : arr) checkContextMatch(a); } private ASTDecRefQueue m_AST_DRQ = new ASTDecRefQueue(); private ASTMapDecRefQueue m_ASTMap_DRQ = new ASTMapDecRefQueue(); private ASTVectorDecRefQueue m_ASTVector_DRQ = new ASTVectorDecRefQueue(); private ApplyResultDecRefQueue m_ApplyResult_DRQ = new ApplyResultDecRefQueue(); private FuncInterpEntryDecRefQueue m_FuncEntry_DRQ = new FuncInterpEntryDecRefQueue(); private FuncInterpDecRefQueue m_FuncInterp_DRQ = new FuncInterpDecRefQueue(); private GoalDecRefQueue m_Goal_DRQ = new GoalDecRefQueue(); private ModelDecRefQueue m_Model_DRQ = new ModelDecRefQueue(); private ParamsDecRefQueue m_Params_DRQ = new ParamsDecRefQueue(); private ParamDescrsDecRefQueue m_ParamDescrs_DRQ = new ParamDescrsDecRefQueue(); private ProbeDecRefQueue m_Probe_DRQ = new ProbeDecRefQueue(); private SolverDecRefQueue m_Solver_DRQ = new SolverDecRefQueue(); private StatisticsDecRefQueue m_Statistics_DRQ = new StatisticsDecRefQueue(); private TacticDecRefQueue m_Tactic_DRQ = new TacticDecRefQueue(); private SimplifierDecRefQueue m_Simplifier_DRQ = new SimplifierDecRefQueue(); private FixedpointDecRefQueue m_Fixedpoint_DRQ = new FixedpointDecRefQueue(); private OptimizeDecRefQueue m_Optimize_DRQ = new OptimizeDecRefQueue(); private ConstructorDecRefQueue m_Constructor_DRQ = new ConstructorDecRefQueue(); private ConstructorListDecRefQueue m_ConstructorList_DRQ = new ConstructorListDecRefQueue(); public IDecRefQueue<Constructor<?>> getConstructorDRQ() { return m_Constructor_DRQ; } public IDecRefQueue<ConstructorList<?>> getConstructorListDRQ() { return m_ConstructorList_DRQ; } public IDecRefQueue<AST> getASTDRQ() { return m_AST_DRQ; } public IDecRefQueue<ASTMap> getASTMapDRQ() { return m_ASTMap_DRQ; } public IDecRefQueue<ASTVector> getASTVectorDRQ() { return m_ASTVector_DRQ; } public IDecRefQueue<ApplyResult> getApplyResultDRQ() { return m_ApplyResult_DRQ; } public IDecRefQueue<FuncInterp.Entry<?>> getFuncEntryDRQ() { return m_FuncEntry_DRQ; } public IDecRefQueue<FuncInterp<?>> getFuncInterpDRQ() { return m_FuncInterp_DRQ; } public IDecRefQueue<Goal> getGoalDRQ() { return m_Goal_DRQ; } public IDecRefQueue<Model> getModelDRQ() { return m_Model_DRQ; } public IDecRefQueue<Params> getParamsDRQ() { return m_Params_DRQ; } public IDecRefQueue<ParamDescrs> getParamDescrsDRQ() { return m_ParamDescrs_DRQ; } public IDecRefQueue<Probe> getProbeDRQ() { return m_Probe_DRQ; } public IDecRefQueue<Solver> getSolverDRQ() { return m_Solver_DRQ; } public IDecRefQueue<Statistics> getStatisticsDRQ() { return m_Statistics_DRQ; } public IDecRefQueue<Tactic> getTacticDRQ() { return m_Tactic_DRQ; } public IDecRefQueue<Simplifier> getSimplifierDRQ() { return m_Simplifier_DRQ; } public IDecRefQueue<Fixedpoint> getFixedpointDRQ() { return m_Fixedpoint_DRQ; } public IDecRefQueue<Optimize> getOptimizeDRQ() { return m_Optimize_DRQ; } /** * Disposes of the context. **/ @Override public void close() { m_AST_DRQ.forceClear(this); m_ASTMap_DRQ.forceClear(this); m_ASTVector_DRQ.forceClear(this); m_ApplyResult_DRQ.forceClear(this); m_FuncEntry_DRQ.forceClear(this); m_FuncInterp_DRQ.forceClear(this); m_Goal_DRQ.forceClear(this); m_Model_DRQ.forceClear(this); m_Params_DRQ.forceClear(this); m_Probe_DRQ.forceClear(this); m_Solver_DRQ.forceClear(this); m_Optimize_DRQ.forceClear(this); m_Statistics_DRQ.forceClear(this); m_Tactic_DRQ.forceClear(this); m_Simplifier_DRQ.forceClear(this); m_Fixedpoint_DRQ.forceClear(this); m_boolSort = null; m_intSort = null; m_realSort = null; m_stringSort = null; synchronized (creation_lock) { Native.delContext(m_ctx); } m_ctx = 0; } }
141,000
30.543848
163
java
z3
z3-master/src/api/java/DatatypeExpr.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: DatatypeExpr.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Datatype expressions **/ public class DatatypeExpr<R extends Sort> extends Expr<DatatypeSort<R>> { /** * Constructor for DatatypeExpr **/ DatatypeExpr(Context ctx, long obj) { super(ctx, obj); } }
452
12.727273
71
java
z3
z3-master/src/api/java/DatatypeSort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: DatatypeSort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Datatype sorts. **/ public class DatatypeSort<R> extends Sort { /** * The number of constructors of the datatype sort. * @throws Z3Exception on error * @return an int **/ public int getNumConstructors() { return Native.getDatatypeSortNumConstructors(getContext().nCtx(), getNativeObject()); } /** * The constructors. * * @throws Z3Exception * @throws Z3Exception on error **/ @SuppressWarnings("unchecked") public FuncDecl<DatatypeSort<R>>[] getConstructors() { int n = getNumConstructors(); FuncDecl<DatatypeSort<R>>[] res = new FuncDecl[n]; for (int i = 0; i < n; i++) res[i] = new FuncDecl<>(getContext(), Native.getDatatypeSortConstructor( getContext().nCtx(), getNativeObject(), i)); return res; } /** * The recognizers. * * @throws Z3Exception * @throws Z3Exception on error **/ @SuppressWarnings("unchecked") public FuncDecl<BoolSort>[] getRecognizers() { int n = getNumConstructors(); FuncDecl<BoolSort>[] res = new FuncDecl[n]; for (int i = 0; i < n; i++) res[i] = new FuncDecl<>(getContext(), Native.getDatatypeSortRecognizer( getContext().nCtx(), getNativeObject(), i)); return res; } /** * The constructor accessors. * * @throws Z3Exception * @throws Z3Exception on error **/ public FuncDecl<?>[][] getAccessors() { int n = getNumConstructors(); FuncDecl<?>[][] res = new FuncDecl[n][]; for (int i = 0; i < n; i++) { FuncDecl<?> fd = new FuncDecl<>(getContext(), Native.getDatatypeSortConstructor(getContext().nCtx(), getNativeObject(), i)); int ds = fd.getDomainSize(); FuncDecl<?>[] tmp = new FuncDecl[ds]; for (int j = 0; j < ds; j++) tmp[j] = new FuncDecl<>(getContext(), Native.getDatatypeSortConstructorAccessor(getContext() .nCtx(), getNativeObject(), i, j)); res[i] = tmp; } return res; } DatatypeSort(Context ctx, long obj) { super(ctx, obj); } DatatypeSort(Context ctx, Symbol name, Constructor<R>[] constructors) { super(ctx, Native.mkDatatype(ctx.nCtx(), name.getNativeObject(), constructors.length, arrayToNative(constructors))); } };
2,806
24.518182
84
java
z3
z3-master/src/api/java/EnumSort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: EnumSort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Enumeration sorts. **/ @SuppressWarnings("unchecked") public class EnumSort<R> extends Sort { /** * The function declarations of the constants in the enumeration. * @throws Z3Exception on error **/ public FuncDecl<EnumSort<R>>[] getConstDecls() { int n = Native.getDatatypeSortNumConstructors(getContext().nCtx(), getNativeObject()); FuncDecl<?>[] t = new FuncDecl[n]; for (int i = 0; i < n; i++) t[i] = new FuncDecl<>(getContext(), Native.getDatatypeSortConstructor(getContext().nCtx(), getNativeObject(), i)); return (FuncDecl<EnumSort<R>>[]) t; } /** * Retrieves the inx'th constant declaration in the enumeration. * @throws Z3Exception on error **/ public FuncDecl<EnumSort<R>> getConstDecl(int inx) { return new FuncDecl<>(getContext(), Native.getDatatypeSortConstructor(getContext().nCtx(), getNativeObject(), inx)); } /** * The constants in the enumeration. * @throws Z3Exception on error * @return an Expr[] **/ public Expr<EnumSort<R>>[] getConsts() { FuncDecl<?>[] cds = getConstDecls(); Expr<?>[] t = new Expr[cds.length]; for (int i = 0; i < t.length; i++) t[i] = getContext().mkApp(cds[i]); return (Expr<EnumSort<R>>[]) t; } /** * Retrieves the inx'th constant in the enumeration. * @throws Z3Exception on error * @return an Expr **/ public Expr<EnumSort<R>> getConst(int inx) { return getContext().mkApp(getConstDecl(inx)); } /** * The test predicates for the constants in the enumeration. * @throws Z3Exception on error **/ @SuppressWarnings("unchecked") public FuncDecl<BoolSort>[] getTesterDecls() { int n = Native.getDatatypeSortNumConstructors(getContext().nCtx(), getNativeObject()); FuncDecl<BoolSort>[] t = new FuncDecl[n]; for (int i = 0; i < n; i++) t[i] = new FuncDecl<>(getContext(), Native.getDatatypeSortRecognizer(getContext().nCtx(), getNativeObject(), i)); return t; } /** * Retrieves the inx'th tester/recognizer declaration in the enumeration. * @throws Z3Exception on error **/ public FuncDecl<BoolSort> getTesterDecl(int inx) { return new FuncDecl<>(getContext(), Native.getDatatypeSortRecognizer(getContext().nCtx(), getNativeObject(), inx)); } EnumSort(Context ctx, Symbol name, Symbol[] enumNames) { super(ctx, Native.mkEnumerationSort(ctx.nCtx(), name.getNativeObject(), enumNames.length, Symbol.arrayToNative(enumNames), new long[enumNames.length], new long[enumNames.length])); } };
2,999
28.126214
126
java
z3
z3-master/src/api/java/Expr.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Expr.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import java.lang.reflect.Type; import java.lang.reflect.ParameterizedType; import com.microsoft.z3.enumerations.Z3_ast_kind; import com.microsoft.z3.enumerations.Z3_decl_kind; import com.microsoft.z3.enumerations.Z3_lbool; import com.microsoft.z3.enumerations.Z3_sort_kind; /* using System; */ /** * Expressions are terms. **/ @SuppressWarnings("unchecked") public class Expr<R extends Sort> extends AST { /** * Returns a simplified version of the expression * @return Expr * @throws Z3Exception on error **/ public Expr<R> simplify() { return simplify(null); } /** * Returns a simplified version of the expression * A set of * parameters * @param p a Params object to configure the simplifier * @see Context#SimplifyHelp * @return an Expr * @throws Z3Exception on error **/ public Expr<R> simplify(Params p) { if (p == null) { return (Expr<R>) Expr.create(getContext(), Native.simplify(getContext().nCtx(), getNativeObject())); } else { return (Expr<R>) Expr.create( getContext(), Native.simplifyEx(getContext().nCtx(), getNativeObject(), p.getNativeObject())); } } /** * The function declaration of the function that is applied in this * expression. * @return a FuncDecl * @throws Z3Exception on error **/ public FuncDecl<R> getFuncDecl() { return new FuncDecl<>(getContext(), Native.getAppDecl(getContext().nCtx(), getNativeObject())); } /** * Indicates whether the expression is the true or false expression or * something else (Z3_L_UNDEF). * @throws Z3Exception on error * @return a Z3_lbool **/ public Z3_lbool getBoolValue() { return Z3_lbool.fromInt(Native.getBoolValue(getContext().nCtx(), getNativeObject())); } /** * The number of arguments of the expression. * @throws Z3Exception on error * @return an int **/ public int getNumArgs() { return Native.getAppNumArgs(getContext().nCtx(), getNativeObject()); } /** * The arguments of the expression. * @throws Z3Exception on error * @return an Expr[] **/ public Expr<?>[] getArgs() { int n = getNumArgs(); Expr<?>[] res = new Expr[n]; for (int i = 0; i < n; i++) { res[i] = Expr.create(getContext(), Native.getAppArg(getContext().nCtx(), getNativeObject(), i)); } return res; } /** * Update the arguments of the expression using the arguments {@code args} * The number of new arguments should coincide with the * current number of arguments. * @param args arguments * @throws Z3Exception on error **/ public Expr<R> update(Expr<?>[] args) { getContext().checkContextMatch(args); if (isApp() && args.length != getNumArgs()) { throw new Z3Exception("Number of arguments does not match"); } return (Expr<R>) Expr.create(getContext(), Native.updateTerm(getContext().nCtx(), getNativeObject(), args.length, Expr.arrayToNative(args))); } /** * Substitute every occurrence of {@code from[i]} in the expression * with {@code to[i]}, for {@code i} smaller than * {@code num_exprs}. * Remarks: The result is the new expression. The * arrays {@code from} and {@code to} must have size * {@code num_exprs}. For every {@code i} smaller than * {@code num_exprs}, we must have that sort of {@code from[i]} * must be equal to sort of {@code to[i]}. * @throws Z3Exception on error * @return an Expr **/ public Expr<R> substitute(Expr<?>[] from, Expr<?>[] to) { getContext().checkContextMatch(from); getContext().checkContextMatch(to); if (from.length != to.length) { throw new Z3Exception("Argument sizes do not match"); } return (Expr<R>) Expr.create(getContext(), Native.substitute(getContext().nCtx(), getNativeObject(), from.length, Expr.arrayToNative(from), Expr.arrayToNative(to))); } /** * Substitute every occurrence of {@code from} in the expression with * {@code to}. * @see Expr#substitute(Expr[],Expr[]) * @throws Z3Exception on error * @return an Expr **/ public Expr<R> substitute(Expr<?> from, Expr<?> to) { return substitute(new Expr[] { from }, new Expr[] { to }); } /** * Substitute the free variables in the expression with the expressions in * {@code to} * Remarks: For every {@code i} smaller than * {@code num_exprs}, the * variable with de-Bruijn index {@code i} * is replaced with term * {@code to[i]}. * @throws Z3Exception on error * @throws Z3Exception on error * @return an Expr **/ public Expr<R> substituteVars(Expr<?>[] to) { getContext().checkContextMatch(to); return (Expr<R>) Expr.create(getContext(), Native.substituteVars(getContext().nCtx(), getNativeObject(), to.length, Expr.arrayToNative(to))); } /** * Translates (copies) the term to the Context {@code ctx}. * * @param ctx A context * * @return A copy of the term which is associated with {@code ctx} * @throws Z3Exception on error **/ public Expr<R> translate(Context ctx) { return (Expr<R>) super.translate(ctx); } /** * Returns a string representation of the expression. **/ @Override public String toString() { return super.toString(); } /** * Indicates whether the term is a numeral * @throws Z3Exception on error * @return a boolean **/ public boolean isNumeral() { return Native.isNumeralAst(getContext().nCtx(), getNativeObject()); } /** * Indicates whether the term is well-sorted. * * @throws Z3Exception on error * @return True if the term is well-sorted, false otherwise. **/ public boolean isWellSorted() { return Native.isWellSorted(getContext().nCtx(), getNativeObject()); } /** * The Sort of the term. * @throws Z3Exception on error * @return a sort **/ public R getSort() { return (R) Sort.create(getContext(), Native.getSort(getContext().nCtx(), getNativeObject())); } /** * Indicates whether the term represents a constant. * @throws Z3Exception on error * @return a boolean **/ public boolean isConst() { return isApp() && getNumArgs() == 0 && getFuncDecl().getDomainSize() == 0; } /** * Indicates whether the term is an integer numeral. * @throws Z3Exception on error * @return a boolean **/ public boolean isIntNum() { return isNumeral() && isInt(); } /** * Indicates whether the term is a real numeral. * @throws Z3Exception on error * @return a boolean **/ public boolean isRatNum() { return isNumeral() && isReal(); } /** * Indicates whether the term is an algebraic number * @throws Z3Exception on error * @return a boolean **/ public boolean isAlgebraicNumber() { return Native.isAlgebraicNumber(getContext().nCtx(), getNativeObject()); } /** * Indicates whether the term has Boolean sort. * @throws Z3Exception on error * @return a boolean **/ public boolean isBool() { return (isExpr() && Native.isEqSort(getContext().nCtx(), Native.mkBoolSort(getContext().nCtx()), Native.getSort(getContext().nCtx(), getNativeObject()))); } /** * Indicates whether the term is the constant true. * @throws Z3Exception on error * @return a boolean **/ public boolean isTrue() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_TRUE; } /** * Indicates whether the term is the constant false. * @throws Z3Exception on error * @return a boolean **/ public boolean isFalse() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_FALSE; } /** * Indicates whether the term is an equality predicate. * @throws Z3Exception on error * @return a boolean **/ public boolean isEq() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_EQ; } /** * Indicates whether the term is an n-ary distinct predicate (every argument * is mutually distinct). * @throws Z3Exception on error * @return a boolean **/ public boolean isDistinct() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_DISTINCT; } /** * Indicates whether the term is a ternary if-then-else term * @throws Z3Exception on error * @return a boolean **/ public boolean isITE() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_ITE; } /** * Indicates whether the term is an n-ary conjunction * @throws Z3Exception on error * @return a boolean **/ public boolean isAnd() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_AND; } /** * Indicates whether the term is an n-ary disjunction * @throws Z3Exception on error * @return a boolean **/ public boolean isOr() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_OR; } /** * Indicates whether the term is an if-and-only-if (Boolean equivalence, * binary) * @throws Z3Exception on error * @return a boolean **/ public boolean isIff() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_IFF; } /** * Indicates whether the term is an exclusive or * @throws Z3Exception on error * @return a boolean **/ public boolean isXor() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_XOR; } /** * Indicates whether the term is a negation * @throws Z3Exception on error * @return a boolean **/ public boolean isNot() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_NOT; } /** * Indicates whether the term is an implication * @throws Z3Exception on error * @return a boolean **/ public boolean isImplies() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_IMPLIES; } /** * Indicates whether the term is of integer sort. * @throws Z3Exception on error * @return a boolean **/ public boolean isInt() { return Native.getSortKind(getContext().nCtx(), Native.getSort(getContext().nCtx(), getNativeObject())) == Z3_sort_kind.Z3_INT_SORT.toInt(); } /** * Indicates whether the term is of sort real. * @throws Z3Exception on error * @return a boolean **/ public boolean isReal() { return Native.getSortKind(getContext().nCtx(), Native.getSort(getContext().nCtx(), getNativeObject())) == Z3_sort_kind.Z3_REAL_SORT.toInt(); } /** * Indicates whether the term is an arithmetic numeral. * @throws Z3Exception on error * @return a boolean **/ public boolean isArithmeticNumeral() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_ANUM; } /** * Indicates whether the term is a less-than-or-equal * @throws Z3Exception on error * @return a boolean **/ public boolean isLE() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_LE; } /** * Indicates whether the term is a greater-than-or-equal * @throws Z3Exception on error * @return a boolean **/ public boolean isGE() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_GE; } /** * Indicates whether the term is a less-than * @throws Z3Exception on error * @return a boolean **/ public boolean isLT() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_LT; } /** * Indicates whether the term is a greater-than * @throws Z3Exception on error * @return a boolean **/ public boolean isGT() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_GT; } /** * Indicates whether the term is addition (binary) * @throws Z3Exception on error * @return a boolean **/ public boolean isAdd() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_ADD; } /** * Indicates whether the term is subtraction (binary) * @throws Z3Exception on error * @return a boolean **/ public boolean isSub() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_SUB; } /** * Indicates whether the term is a unary minus * @throws Z3Exception on error * @return a boolean **/ public boolean isUMinus() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_UMINUS; } /** * Indicates whether the term is multiplication (binary) * @throws Z3Exception on error * @return a boolean **/ public boolean isMul() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_MUL; } /** * Indicates whether the term is division (binary) * @throws Z3Exception on error * @return a boolean **/ public boolean isDiv() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_DIV; } /** * Indicates whether the term is integer division (binary) * @throws Z3Exception on error * @return a boolean **/ public boolean isIDiv() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_IDIV; } /** * Indicates whether the term is remainder (binary) * @throws Z3Exception on error * @return a boolean **/ public boolean isRemainder() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_REM; } /** * Indicates whether the term is modulus (binary) * @throws Z3Exception on error * @return a boolean **/ public boolean isModulus() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_MOD; } /** * Indicates whether the term is a coercion of integer to real (unary) * @throws Z3Exception on error * @return a boolean **/ public boolean isIntToReal() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_TO_REAL; } /** * Indicates whether the term is a coercion of real to integer (unary) * @throws Z3Exception on error * @return a boolean **/ public boolean isRealToInt() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_TO_INT; } /** * Indicates whether the term is a check that tests whether a real is * integral (unary) * @throws Z3Exception on error * @return a boolean **/ public boolean isRealIsInt() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_IS_INT; } /** * Indicates whether the term is of an array sort. * @throws Z3Exception on error * @return a boolean **/ public boolean isArray() { return (Native.isApp(getContext().nCtx(), getNativeObject()) && Z3_sort_kind .fromInt(Native.getSortKind(getContext().nCtx(), Native.getSort(getContext().nCtx(), getNativeObject()))) == Z3_sort_kind.Z3_ARRAY_SORT); } /** * Indicates whether the term is an array store. * Remarks: It satisfies * select(store(a,i,v),j) = if i = j then v else select(a,j). Array store * takes at least 3 arguments. * @throws Z3Exception on error * @return a boolean **/ public boolean isStore() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_STORE; } /** * Indicates whether the term is an array select. * @throws Z3Exception on error * @return a boolean **/ public boolean isSelect() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_SELECT; } /** * Indicates whether the term is a constant array. * Remarks: For example, * select(const(v),i) = v holds for every v and i. The function is * unary. * @throws Z3Exception on error * @return a boolean **/ public boolean isConstantArray() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_CONST_ARRAY; } /** * Indicates whether the term is a default array. * Remarks: For example default(const(v)) = v. The function is unary. * @throws Z3Exception on error * @return a boolean **/ public boolean isDefaultArray() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_ARRAY_DEFAULT; } /** * Indicates whether the term is an array map. * Remarks: It satisfies * map[f](a1,..,a_n)[i] = f(a1[i],...,a_n[i]) for every i. * @throws Z3Exception on error * @return a boolean **/ public boolean isArrayMap() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_ARRAY_MAP; } /** * Indicates whether the term is an as-array term. * Remarks: An as-array term * is n array value that behaves as the function graph of the function * passed as parameter. * @throws Z3Exception on error * @return a boolean **/ public boolean isAsArray() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_AS_ARRAY; } /** * Indicates whether the term is set union * @throws Z3Exception on error * @return a boolean **/ public boolean isSetUnion() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_SET_UNION; } /** * Indicates whether the term is set intersection * @throws Z3Exception on error * @return a boolean **/ public boolean isSetIntersect() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_SET_INTERSECT; } /** * Indicates whether the term is set difference * @throws Z3Exception on error * @return a boolean **/ public boolean isSetDifference() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_SET_DIFFERENCE; } /** * Indicates whether the term is set complement * @throws Z3Exception on error * @return a boolean **/ public boolean isSetComplement() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_SET_COMPLEMENT; } /** * Indicates whether the term is set subset * @throws Z3Exception on error * @return a boolean **/ public boolean isSetSubset() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_SET_SUBSET; } /** * Indicates whether the terms is of bit-vector sort. * @throws Z3Exception on error * @return a boolean **/ public boolean isBV() { return Native.getSortKind(getContext().nCtx(), Native.getSort(getContext().nCtx(), getNativeObject())) == Z3_sort_kind.Z3_BV_SORT .toInt(); } /** * Indicates whether the term is a bit-vector numeral * @throws Z3Exception on error * @return a boolean **/ public boolean isBVNumeral() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BNUM; } /** * Indicates whether the term is a one-bit bit-vector with value one * @throws Z3Exception on error * @return a boolean **/ public boolean isBVBitOne() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BIT1; } /** * Indicates whether the term is a one-bit bit-vector with value zero * @throws Z3Exception on error * @return a boolean **/ public boolean isBVBitZero() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BIT0; } /** * Indicates whether the term is a bit-vector unary minus * @throws Z3Exception on error * @return a boolean **/ public boolean isBVUMinus() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BNEG; } /** * Indicates whether the term is a bit-vector addition (binary) * @throws Z3Exception on error * @return a boolean **/ public boolean isBVAdd() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BADD; } /** * Indicates whether the term is a bit-vector subtraction (binary) * @throws Z3Exception on error * @return a boolean **/ public boolean isBVSub() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BSUB; } /** * Indicates whether the term is a bit-vector multiplication (binary) * @throws Z3Exception on error * @return a boolean **/ public boolean isBVMul() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BMUL; } /** * Indicates whether the term is a bit-vector signed division (binary) * @throws Z3Exception on error * @return a boolean **/ public boolean isBVSDiv() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BSDIV; } /** * Indicates whether the term is a bit-vector unsigned division (binary) * @throws Z3Exception on error * @return a boolean **/ public boolean isBVUDiv() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BUDIV; } /** * Indicates whether the term is a bit-vector signed remainder (binary) * @throws Z3Exception on error * @return a boolean **/ public boolean isBVSRem() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BSREM; } /** * Indicates whether the term is a bit-vector unsigned remainder (binary) * @throws Z3Exception on error * @return a boolean **/ public boolean isBVURem() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BUREM; } /** * Indicates whether the term is a bit-vector signed modulus * @throws Z3Exception on error * @return a boolean **/ public boolean isBVSMod() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BSMOD; } /** * Indicates whether the term is a bit-vector signed division by zero * @return a boolean * @throws Z3Exception on error **/ boolean isBVSDiv0() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BSDIV0; } /** * Indicates whether the term is a bit-vector unsigned division by zero * @return a boolean * @throws Z3Exception on error **/ boolean isBVUDiv0() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BUDIV0; } /** * Indicates whether the term is a bit-vector signed remainder by zero * @return a boolean * @throws Z3Exception on error **/ boolean isBVSRem0() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BSREM0; } /** * Indicates whether the term is a bit-vector unsigned remainder by zero * @return a boolean * @throws Z3Exception on error **/ boolean isBVURem0() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BUREM0; } /** * Indicates whether the term is a bit-vector signed modulus by zero * @return a boolean * @throws Z3Exception on error **/ boolean isBVSMod0() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BSMOD0; } /** * Indicates whether the term is an unsigned bit-vector less-than-or-equal * @throws Z3Exception on error * @return a boolean **/ public boolean isBVULE() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_ULEQ; } /** * Indicates whether the term is a signed bit-vector less-than-or-equal * @throws Z3Exception on error * @return a boolean **/ public boolean isBVSLE() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_SLEQ; } /** * Indicates whether the term is an unsigned bit-vector * greater-than-or-equal * @throws Z3Exception on error * @return a boolean **/ public boolean isBVUGE() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_UGEQ; } /** * Indicates whether the term is a signed bit-vector greater-than-or-equal * @throws Z3Exception on error * @return a boolean **/ public boolean isBVSGE() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_SGEQ; } /** * Indicates whether the term is an unsigned bit-vector less-than * @throws Z3Exception on error * @return a boolean **/ public boolean isBVULT() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_ULT; } /** * Indicates whether the term is a signed bit-vector less-than * @throws Z3Exception on error * @return a boolean **/ public boolean isBVSLT() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_SLT; } /** * Indicates whether the term is an unsigned bit-vector greater-than * @throws Z3Exception on error * @return a boolean **/ public boolean isBVUGT() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_UGT; } /** * Indicates whether the term is a signed bit-vector greater-than * @throws Z3Exception on error * @return a boolean **/ public boolean isBVSGT() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_SGT; } /** * Indicates whether the term is a bit-wise AND * @throws Z3Exception on error * @return a boolean **/ public boolean isBVAND() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BAND; } /** * Indicates whether the term is a bit-wise OR * @throws Z3Exception on error * @return a boolean **/ public boolean isBVOR() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BOR; } /** * Indicates whether the term is a bit-wise NOT * @throws Z3Exception on error * @return a boolean **/ public boolean isBVNOT() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BNOT; } /** * Indicates whether the term is a bit-wise XOR * @throws Z3Exception on error * @return a boolean **/ public boolean isBVXOR() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BXOR; } /** * Indicates whether the term is a bit-wise NAND * @throws Z3Exception on error * @return a boolean **/ public boolean isBVNAND() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BNAND; } /** * Indicates whether the term is a bit-wise NOR * @throws Z3Exception on error * @return a boolean **/ public boolean isBVNOR() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BNOR; } /** * Indicates whether the term is a bit-wise XNOR * @throws Z3Exception on error * @return a boolean **/ public boolean isBVXNOR() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BXNOR; } /** * Indicates whether the term is a bit-vector concatenation (binary) * @throws Z3Exception on error * @return a boolean **/ public boolean isBVConcat() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_CONCAT; } /** * Indicates whether the term is a bit-vector sign extension * @throws Z3Exception on error * @return a boolean **/ public boolean isBVSignExtension() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_SIGN_EXT; } /** * Indicates whether the term is a bit-vector zero extension * @throws Z3Exception on error * @return a boolean **/ public boolean isBVZeroExtension() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_ZERO_EXT; } /** * Indicates whether the term is a bit-vector extraction * @throws Z3Exception on error * @return a boolean **/ public boolean isBVExtract() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_EXTRACT; } /** * Indicates whether the term is a bit-vector repetition * @throws Z3Exception on error * @return a boolean **/ public boolean isBVRepeat() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_REPEAT; } /** * Indicates whether the term is a bit-vector reduce OR * @throws Z3Exception on error * @return a boolean **/ public boolean isBVReduceOR() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BREDOR; } /** * Indicates whether the term is a bit-vector reduce AND * @throws Z3Exception on error * @return a boolean **/ public boolean isBVReduceAND() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BREDAND; } /** * Indicates whether the term is a bit-vector comparison * @throws Z3Exception on error * @return a boolean **/ public boolean isBVComp() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BCOMP; } /** * Indicates whether the term is a bit-vector shift left * @throws Z3Exception on error * @return a boolean **/ public boolean isBVShiftLeft() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BSHL; } /** * Indicates whether the term is a bit-vector logical shift right * @throws Z3Exception on error * @return a boolean **/ public boolean isBVShiftRightLogical() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BLSHR; } /** * Indicates whether the term is a bit-vector arithmetic shift left * @throws Z3Exception on error * @return a boolean **/ public boolean isBVShiftRightArithmetic() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BASHR; } /** * Indicates whether the term is a bit-vector rotate left * @throws Z3Exception on error * @return a boolean **/ public boolean isBVRotateLeft() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_ROTATE_LEFT; } /** * Indicates whether the term is a bit-vector rotate right * @throws Z3Exception on error * @return a boolean **/ public boolean isBVRotateRight() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_ROTATE_RIGHT; } /** * Indicates whether the term is a bit-vector rotate left (extended) * Remarks: Similar to Z3_OP_ROTATE_LEFT, but it is a binary operator * instead of a parametric one. * @throws Z3Exception on error * @return a boolean **/ public boolean isBVRotateLeftExtended() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_EXT_ROTATE_LEFT; } /** * Indicates whether the term is a bit-vector rotate right (extended) * Remarks: Similar to Z3_OP_ROTATE_RIGHT, but it is a binary operator * instead of a parametric one. * @throws Z3Exception on error * @return a boolean **/ public boolean isBVRotateRightExtended() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_EXT_ROTATE_RIGHT; } /** * Indicates whether the term is a coercion from integer to bit-vector * * Remarks: This function is not supported by the decision procedures. Only * the most rudimentary simplification rules are applied to this * function. * @throws Z3Exception on error * @return a boolean **/ public boolean isIntToBV() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_INT2BV; } /** * Indicates whether the term is a coercion from bit-vector to integer * * Remarks: This function is not supported by the decision procedures. Only * the most rudimentary simplification rules are applied to this * function. * @throws Z3Exception on error * @return a boolean **/ public boolean isBVToInt() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_BV2INT; } /** * Indicates whether the term is a bit-vector carry * Remarks: Compute the * carry bit in a full-adder. The meaning is given by the equivalence (carry * l1 l2 l3) &lt;=&gt; (or (and l1 l2) (and l1 l3) (and l2 l3))) * @throws Z3Exception on error * @return a boolean **/ public boolean isBVCarry() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_CARRY; } /** * Indicates whether the term is a bit-vector ternary XOR * Remarks: The * meaning is given by the equivalence (xor3 l1 l2 l3) &lt;=&gt; (xor (xor * l1 l2) l3) * @throws Z3Exception on error * @return a boolean **/ public boolean isBVXOR3() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_XOR3; } /** * Indicates whether the term is a label (used by the Boogie Verification * condition generator). * Remarks: The label has two parameters, a string and * a Boolean polarity. It takes one argument, a formula. * @throws Z3Exception on error * @return a boolean **/ public boolean isLabel() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_LABEL; } /** * Indicates whether the term is a label literal (used by the Boogie * Verification condition generator). * Remarks: A label literal has a set of * string parameters. It takes no arguments. * @throws Z3Exception on error * @return a boolean **/ public boolean isLabelLit() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_LABEL_LIT; } /** * Check whether expression is a string constant. * @return a boolean */ public boolean isString() { return isApp() && Native.isString(getContext().nCtx(), getNativeObject()); } /** * Retrieve string corresponding to string constant. * Remark: the expression should be a string constant, (isString() should return true). * @throws Z3Exception on error * @return a string */ public String getString() { return Native.getString(getContext().nCtx(), getNativeObject()); } /** * TBD: sketch for #2522, 'Pointer' seems deprecated and instead * approach seems to be around Set/Get CharArrayRegion and updating Native.cpp * code generation to produce the char[]. * public char[] getNativeString() { Native.IntPtr len = new Native.IntPtr(); long s = Native.getLstring(getContext().nCtx(), getNativeObject(), len); char[] result = new char[len.value]; Pointer ptr = Pointer.createConstant(s); for (int i = 0; i < len.value; ++i) result[i] = ptr.getChar(i); return result; } */ /** * Check whether expression is a concatenation * @return a boolean */ public boolean isConcat() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_SEQ_CONCAT; } /** * Indicates whether the term is a binary equivalence modulo namings. * Remarks: This binary predicate is used in proof terms. It captures * equisatisfiability and equivalence modulo renamings. * @throws Z3Exception on error * @return a boolean **/ public boolean isOEQ() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_OEQ; } /** * Indicates whether the term is a Proof for the expression 'true'. * @throws Z3Exception on error * @return a boolean **/ public boolean isProofTrue() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_TRUE; } /** * Indicates whether the term is a proof for a fact asserted by the user. * @throws Z3Exception on error * @return a boolean **/ public boolean isProofAsserted() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_ASSERTED; } /** * Indicates whether the term is a proof for a fact (tagged as goal) * asserted by the user. * @throws Z3Exception on error * @return a boolean **/ public boolean isProofGoal() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_GOAL; } /** * Indicates whether the term is proof via modus ponens * Remarks: Given a * proof for p and a proof for (implies p q), produces a proof for q. T1: p * T2: (implies p q) [mp T1 T2]: q The second antecedents may also be a * proof for (iff p q). * @throws Z3Exception on error * @return a boolean **/ public boolean isProofModusPonens() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_MODUS_PONENS; } /** * Indicates whether the term is a proof for (R t t), where R is a reflexive * relation. * Remarks: This proof object has no antecedents. The only * reflexive relations that are used are equivalence modulo namings, * equality and equivalence. That is, R is either '~', '=' or * 'iff'. * @throws Z3Exception on error * @return a boolean **/ public boolean isProofReflexivity() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_REFLEXIVITY; } /** * Indicates whether the term is proof by symmetricity of a relation * * Remarks: Given an symmetric relation R and a proof for (R t s), produces * a proof for (R s t). T1: (R t s) [symmetry T1]: (R s t) T1 is the * antecedent of this proof object. * @throws Z3Exception on error * @return a boolean **/ public boolean isProofSymmetry() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_SYMMETRY; } /** * Indicates whether the term is a proof by transitivity of a relation * * Remarks: Given a transitive relation R, and proofs for (R t s) and (R s * u), produces a proof for (R t u). T1: (R t s) T2: (R s u) [trans T1 T2]: * (R t u) * @throws Z3Exception on error * @return a boolean **/ public boolean isProofTransitivity() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_TRANSITIVITY; } /** * Indicates whether the term is a proof by condensed transitivity of a * relation * Remarks: Condensed transitivity proof. It combines several symmetry * and transitivity proofs. Example: T1: (R a b) T2: (R c b) T3: (R c d) * [trans* T1 T2 T3]: (R a d) R must be a symmetric and transitive relation. * * Assuming that this proof object is a proof for (R s t), then a proof * checker must check if it is possible to prove (R s t) using the * antecedents, symmetry and transitivity. That is, if there is a path from * s to t, if we view every antecedent (R a b) as an edge between a and b. * * @throws Z3Exception on error * @return a boolean **/ public boolean isProofTransitivityStar() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_TRANSITIVITY_STAR; } /** * Indicates whether the term is a monotonicity proof object. * Remarks: T1: * (R t_1 s_1) ... Tn: (R t_n s_n) [monotonicity T1 ... Tn]: (R (f t_1 ... * t_n) (f s_1 ... s_n)) Remark: if t_i == s_i, then the antecedent Ti is * suppressed. That is, reflexivity proofs are suppressed to save space. * * @throws Z3Exception on error * @return a boolean **/ public boolean isProofMonotonicity() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_MONOTONICITY; } /** * Indicates whether the term is a quant-intro proof * Remarks: Given a proof * for (~ p q), produces a proof for (~ (forall (x) p) (forall (x) q)). T1: * (~ p q) [quant-intro T1]: (~ (forall (x) p) (forall (x) q)) * @throws Z3Exception on error * @return a boolean **/ public boolean isProofQuantIntro() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_QUANT_INTRO; } /** * Indicates whether the term is a distributivity proof object. * Remarks: * Given that f (= or) distributes over g (= and), produces a proof for (= * (f a (g c d)) (g (f a c) (f a d))) If f and g are associative, this proof * also justifies the following equality: (= (f (g a b) (g c d)) (g (f a c) * (f a d) (f b c) (f b d))) where each f and g can have arbitrary number of * arguments. * * This proof object has no antecedents. Remark. This rule is used by the * CNF conversion pass and instantiated by f = or, and g = and. * @throws Z3Exception on error * @return a boolean **/ public boolean isProofDistributivity() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_DISTRIBUTIVITY; } /** * Indicates whether the term is a proof by elimination of AND * Remarks: * Given a proof for (and l_1 ... l_n), produces a proof for l_i T1: (and * l_1 ... l_n) [and-elim T1]: l_i * @throws Z3Exception on error * @return a boolean **/ public boolean isProofAndElimination() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_AND_ELIM; } /** * Indicates whether the term is a proof by elimination of not-or * Remarks: * Given a proof for (not (or l_1 ... l_n)), produces a proof for (not l_i). * T1: (not (or l_1 ... l_n)) [not-or-elim T1]: (not l_i) * @throws Z3Exception on error * @return a boolean **/ public boolean isProofOrElimination() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_NOT_OR_ELIM; } /** * Indicates whether the term is a proof by rewriting * Remarks: A proof for * a local rewriting step (= t s). The head function symbol of t is * interpreted. * * This proof object has no antecedents. The conclusion of a rewrite rule is * either an equality (= t s), an equivalence (iff t s), or * equi-satisfiability (~ t s). Remark: if f is bool, then = is iff. * * Examples: (= (+ x 0) x) (= (+ x 1 2) (+ 3 x)) (iff (or x false) x) * * @throws Z3Exception on error * @return a boolean **/ public boolean isProofRewrite() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_REWRITE; } /** * Indicates whether the term is a proof by rewriting * Remarks: A proof for * rewriting an expression t into an expression s. This proof object can have n * antecedents. The antecedents are proofs for equalities used as * substitution rules. The object is used in a few cases . The cases are: - When applying contextual * simplification (CONTEXT_SIMPLIFIER=true) - When converting bit-vectors to * Booleans (BIT2BOOL=true) * @throws Z3Exception on error * @return a boolean **/ public boolean isProofRewriteStar() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_REWRITE_STAR; } /** * Indicates whether the term is a proof for pulling quantifiers out. * Remarks: A proof for (iff (f (forall (x) q(x)) r) (forall (x) (f (q x) * r))). This proof object has no antecedents. * @throws Z3Exception on error * @return a boolean **/ public boolean isProofPullQuant() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_PULL_QUANT; } /** * Indicates whether the term is a proof for pushing quantifiers in. * Remarks: A proof for: (iff (forall (x_1 ... x_m) (and p_1[x_1 ... x_m] * ... p_n[x_1 ... x_m])) (and (forall (x_1 ... x_m) p_1[x_1 ... x_m]) ... * (forall (x_1 ... x_m) p_n[x_1 ... x_m]))) This proof object has no * antecedents * @throws Z3Exception on error * @return a boolean **/ public boolean isProofPushQuant() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_PUSH_QUANT; } /** * Indicates whether the term is a proof for elimination of unused * variables. * Remarks: A proof for (iff (forall (x_1 ... x_n y_1 ... y_m) * p[x_1 ... x_n]) (forall (x_1 ... x_n) p[x_1 ... x_n])) * * It is used to justify the elimination of unused variables. This proof * object has no antecedents. * @throws Z3Exception on error * @return a boolean **/ public boolean isProofElimUnusedVars() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_ELIM_UNUSED_VARS; } /** * Indicates whether the term is a proof for destructive equality resolution * Remarks: A proof for destructive equality resolution: (iff (forall (x) * (or (not (= x t)) P[x])) P[t]) if x does not occur in t. * * This proof object has no antecedents. * * Several variables can be eliminated simultaneously. * @throws Z3Exception on error * @return a boolean **/ public boolean isProofDER() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_DER; } /** * Indicates whether the term is a proof for quantifier instantiation * * Remarks: A proof of (or (not (forall (x) (P x))) (P a)) * @throws Z3Exception on error * @return a boolean **/ public boolean isProofQuantInst() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_QUANT_INST; } /** * Indicates whether the term is a hypothesis marker. * Remarks: Mark a * hypothesis in a natural deduction style proof. * @throws Z3Exception on error * @return a boolean **/ public boolean isProofHypothesis() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_HYPOTHESIS; } /** * Indicates whether the term is a proof by lemma * Remarks: T1: false [lemma * T1]: (or (not l_1) ... (not l_n)) * * This proof object has one antecedent: a hypothetical proof for false. It * converts the proof in a proof for (or (not l_1) ... (not l_n)), when T1 * contains the hypotheses: l_1, ..., l_n. * @throws Z3Exception on error * @return a boolean **/ public boolean isProofLemma() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_LEMMA; } /** * Indicates whether the term is a proof by unit resolution * Remarks: T1: * (or l_1 ... l_n l_1' ... l_m') T2: (not l_1) ... R(n+1): (not l_n) * [unit-resolution T1 ... R(n+1)]: (or l_1' ... l_m') * @throws Z3Exception on error * @return a boolean **/ public boolean isProofUnitResolution() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_UNIT_RESOLUTION; } /** * Indicates whether the term is a proof by iff-true * Remarks: T1: p * [iff-true T1]: (iff p true) * @throws Z3Exception on error * @return a boolean **/ public boolean isProofIFFTrue() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_IFF_TRUE; } /** * Indicates whether the term is a proof by iff-false * Remarks: T1: (not p) * [iff-false T1]: (iff p false) * @throws Z3Exception on error * @return a boolean **/ public boolean isProofIFFFalse() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_IFF_FALSE; } /** * Indicates whether the term is a proof by commutativity * Remarks: [comm]: * (= (f a b) (f b a)) * * f is a commutative operator. * * This proof object has no antecedents. Remark: if f is bool, then = is * iff. * @throws Z3Exception on error * @return a boolean **/ public boolean isProofCommutativity() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_COMMUTATIVITY; } /** * Indicates whether the term is a proof for Tseitin-like axioms * Remarks: * Proof object used to justify Tseitin's like axioms: * * (or (not (and p q)) p) (or (not (and p q)) q) (or (not (and p q r)) p) * (or (not (and p q r)) q) (or (not (and p q r)) r) ... (or (and p q) (not * p) (not q)) (or (not (or p q)) p q) (or (or p q) (not p)) (or (or p q) * (not q)) (or (not (iff p q)) (not p) q) (or (not (iff p q)) p (not q)) * (or (iff p q) (not p) (not q)) (or (iff p q) p q) (or (not (ite a b c)) * (not a) b) (or (not (ite a b c)) a c) (or (ite a b c) (not a) (not b)) * (or (ite a b c) a (not c)) (or (not (not a)) (not a)) (or (not a) a) * * This proof object has no antecedents. Note: all axioms are propositional * tautologies. Note also that 'and' and 'or' can take multiple arguments. * You can recover the propositional tautologies by unfolding the Boolean * connectives in the axioms a small bounded number of steps (=3). * * @throws Z3Exception on error * @return a boolean **/ public boolean isProofDefAxiom() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_DEF_AXIOM; } /** * Indicates whether the term is a proof for introduction of a name * Remarks: Introduces a name for a formula/term. Suppose e is an * expression with free variables x, and def-intro introduces the name n(x). * The possible cases are: * * When e is of Boolean type: [def-intro]: (and (or n (not e)) (or (not n) * e)) * * or: [def-intro]: (or (not n) e) when e only occurs positively. * * When e is of the form (ite cond th el): [def-intro]: (and (or (not cond) * (= n th)) (or cond (= n el))) * * Otherwise: [def-intro]: (= n e) * @throws Z3Exception on error * @return a boolean **/ public boolean isProofDefIntro() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_DEF_INTRO; } /** * Indicates whether the term is a proof for application of a definition * Remarks: [apply-def T1]: F ~ n F is 'equivalent' to n, given that T1 is * a proof that n is a name for F. * @throws Z3Exception on error * @return a boolean **/ public boolean isProofApplyDef() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_APPLY_DEF; } /** * Indicates whether the term is a proof iff-oeq * Remarks: T1: (iff p q) * [iff~ T1]: (~ p q) * @throws Z3Exception on error * @return a boolean **/ public boolean isProofIFFOEQ() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_IFF_OEQ; } /** * Indicates whether the term is a proof for a positive NNF step * Remarks: * Proof for a (positive) NNF step. Example: * * T1: (not s_1) ~ r_1 T2: (not s_2) ~ r_2 T3: s_1 ~ r_1' T4: s_2 ~ r_2' * [nnf-pos T1 T2 T3 T4]: (~ (iff s_1 s_2) (and (or r_1 r_2') (or r_1' * r_2))) * * The negation normal form steps NNF_POS and NNF_NEG are used in the * following cases: (a) When creating the NNF of a positive force * quantifier. The quantifier is retained (unless the bound variables are * eliminated). Example T1: q ~ q_new [nnf-pos T1]: (~ (forall (x R) q) * (forall (x R) q_new)) * * (b) When recursively creating NNF over Boolean formulas, where the * top-level connective is changed during NNF conversion. The relevant * Boolean connectives for NNF_POS are 'implies', 'iff', 'xor', 'ite'. * NNF_NEG furthermore handles the case where negation is pushed over * Boolean connectives 'and' and 'or'. * @throws Z3Exception on error * @return a boolean **/ public boolean isProofNNFPos() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_NNF_POS; } /** * Indicates whether the term is a proof for a negative NNF step * Remarks: * Proof for a (negative) NNF step. Examples: * * T1: (not s_1) ~ r_1 ... Tn: (not s_n) ~ r_n [nnf-neg T1 ... Tn]: (not * (and s_1 ... s_n)) ~ (or r_1 ... r_n) and T1: (not s_1) ~ r_1 ... Tn: * (not s_n) ~ r_n [nnf-neg T1 ... Tn]: (not (or s_1 ... s_n)) ~ (and r_1 * ... r_n) and T1: (not s_1) ~ r_1 T2: (not s_2) ~ r_2 T3: s_1 ~ r_1' T4: * s_2 ~ r_2' [nnf-neg T1 T2 T3 T4]: (~ (not (iff s_1 s_2)) (and (or r_1 * r_2) (or r_1' r_2'))) * @throws Z3Exception on error * @return a boolean **/ public boolean isProofNNFNeg() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_NNF_NEG; } /** * Indicates whether the term is a proof for a Skolemization step * Remarks: * Proof for: * * [sk]: (~ (not (forall x (p x y))) (not (p (sk y) y))) [sk]: (~ (exists x * (p x y)) (p (sk y) y)) * * This proof object has no antecedents. * @throws Z3Exception on error * @return a boolean **/ public boolean isProofSkolemize() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_SKOLEMIZE; } /** * Indicates whether the term is a proof by modus ponens for * equi-satisfiability. * Remarks: Modus ponens style rule for * equi-satisfiability. T1: p T2: (~ p q) [mp~ T1 T2]: q * @throws Z3Exception on error * @return a boolean **/ public boolean isProofModusPonensOEQ() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_MODUS_PONENS_OEQ; } /** * Indicates whether the term is a proof for theory lemma * Remarks: Generic * proof for theory lemmas. * * The theory lemma function comes with one or more parameters. The first * parameter indicates the name of the theory. For the theory of arithmetic, * additional parameters provide hints for checking the theory lemma. The * hints for arithmetic are: - farkas - followed by rational coefficients. * Multiply the coefficients to the inequalities in the lemma, add the * (negated) inequalities and obtain a contradiction. - triangle-eq - * Indicates a lemma related to the equivalence: (iff (= t1 t2) (and (&lt;= * t1 t2) (&lt;= t2 t1))) - gcd-test - Indicates an integer linear * arithmetic lemma that uses a gcd test. * @throws Z3Exception on error * @return a boolean **/ public boolean isProofTheoryLemma() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_PR_TH_LEMMA; } /** * Indicates whether the term is of an array sort. * @throws Z3Exception on error * @return a boolean **/ public boolean isRelation() { return (Native.isApp(getContext().nCtx(), getNativeObject()) && Native .getSortKind(getContext().nCtx(), Native.getSort(getContext().nCtx(), getNativeObject())) == Z3_sort_kind.Z3_RELATION_SORT .toInt()); } /** * Indicates whether the term is an relation store * Remarks: Insert a record * into a relation. The function takes {@code n+1} arguments, where the * first argument is the relation and the remaining {@code n} elements * correspond to the {@code n} columns of the relation. * @throws Z3Exception on error * @return a boolean **/ public boolean isRelationStore() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_RA_STORE; } /** * Indicates whether the term is an empty relation * @throws Z3Exception on error * @return a boolean **/ public boolean isEmptyRelation() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_RA_EMPTY; } /** * Indicates whether the term is a test for the emptiness of a relation * @throws Z3Exception on error * @return a boolean **/ public boolean isIsEmptyRelation() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_RA_IS_EMPTY; } /** * Indicates whether the term is a relational join * @throws Z3Exception on error * @return a boolean **/ public boolean isRelationalJoin() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_RA_JOIN; } /** * Indicates whether the term is the union or convex hull of two relations. * * Remarks: The function takes two arguments. * @throws Z3Exception on error * @return a boolean **/ public boolean isRelationUnion() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_RA_UNION; } /** * Indicates whether the term is the widening of two relations * Remarks: The * function takes two arguments. * @throws Z3Exception on error * @return a boolean **/ public boolean isRelationWiden() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_RA_WIDEN; } /** * Indicates whether the term is a projection of columns (provided as * numbers in the parameters). * Remarks: The function takes one * argument. * @throws Z3Exception on error * @return a boolean **/ public boolean isRelationProject() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_RA_PROJECT; } /** * Indicates whether the term is a relation filter * Remarks: Filter * (restrict) a relation with respect to a predicate. The first argument is * a relation. The second argument is a predicate with free de-Bruijn * indices corresponding to the columns of the relation. So the first column * in the relation has index 0. * @throws Z3Exception on error * @return a boolean **/ public boolean isRelationFilter() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_RA_FILTER; } /** * Indicates whether the term is an intersection of a relation with the * negation of another. * Remarks: Intersect the first relation with respect * to negation of the second relation (the function takes two arguments). * Logically, the specification can be described by a function * * target = filter_by_negation(pos, neg, columns) * * where columns are pairs c1, d1, .., cN, dN of columns from pos and neg, * such that target are elements in x in pos, such that there is no y in neg * that agrees with x on the columns c1, d1, .., cN, dN. * @throws Z3Exception on error * @return a boolean **/ public boolean isRelationNegationFilter() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_RA_NEGATION_FILTER; } /** * Indicates whether the term is the renaming of a column in a relation * Remarks: The function takes one argument. The parameters contain the * renaming as a cycle. * @throws Z3Exception on error * @return a boolean **/ public boolean isRelationRename() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_RA_RENAME; } /** * Indicates whether the term is the complement of a relation * @throws Z3Exception on error * @return a boolean **/ public boolean isRelationComplement() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_RA_COMPLEMENT; } /** * Indicates whether the term is a relational select * Remarks: Check if a * record is an element of the relation. The function takes {@code n+1} * arguments, where the first argument is a relation, and the remaining * {@code n} arguments correspond to a record. * @throws Z3Exception on error * @return a boolean **/ public boolean isRelationSelect() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_RA_SELECT; } /** * Indicates whether the term is a relational clone (copy) * Remarks: Create * a fresh copy (clone) of a relation. The function is logically the * identity, but in the context of a register machine allows for terms of * kind {@code isRelationUnion} to perform destructive updates to * the first argument. * @see #isRelationUnion * @throws Z3Exception on error * @return a boolean **/ public boolean isRelationClone() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_RA_CLONE; } /** * Indicates whether the term is of an array sort. * @throws Z3Exception on error * @return a boolean **/ public boolean isFiniteDomain() { return (Native.isApp(getContext().nCtx(), getNativeObject()) && Native .getSortKind(getContext().nCtx(), Native.getSort(getContext().nCtx(), getNativeObject())) == Z3_sort_kind.Z3_FINITE_DOMAIN_SORT .toInt()); } /** * Indicates whether the term is a less than predicate over a finite domain. * @throws Z3Exception on error * @return a boolean **/ public boolean isFiniteDomainLT() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_FD_LT; } /** * The de-Bruijn index of a bound variable. * Remarks: Bound variables are * indexed by de-Bruijn indices. It is perhaps easiest to explain the * meaning of de-Bruijn indices by indicating the compilation process from * non-de-Bruijn formulas to de-Bruijn format. {@code * abs(forall (x1) phi) = forall (x1) abs1(phi, x1, 0) * abs(forall (x1, x2) phi) = abs(forall (x1) abs(forall (x2) phi)) * abs1(x, x, n) = b_n * abs1(y, x, n) = y * abs1(f(t1,...,tn), x, n) = f(abs1(t1,x,n), ..., abs1(tn,x,n)) * abs1(forall (x1) phi, x, n) = forall (x1) (abs1(phi, x, n+1)) * } The last line is significant: the index of a bound variable is * different depending on the scope in which it appears. The deeper x * appears, the higher is its index. * @throws Z3Exception on error * @return an int **/ public int getIndex() { if (!isVar()) { throw new Z3Exception("Term is not a bound variable."); } return Native.getIndexValue(getContext().nCtx(), getNativeObject()); } private Class sort = null; /** * Downcast sort of this expression. {@code * Expr<ArithSort> mixedExpr = ctx.mkDiv(ctx.mkReal(1), ctx.mkInt(2)); * Expr<RealSort> realExpr = mixedExpr.distillSort(RealSort.class) * } * * @throws Z3Exception if sort is not compatible with expr. **/ public <S extends R> Expr<S> distillSort(Class<S> newSort) { if (sort != null && !newSort.isAssignableFrom(sort)) { throw new Z3Exception( String.format("Cannot distill expression of sort %s to %s.", sort.getName(), newSort.getName())); } return (Expr<S>) ((Expr<?>) this); } /** * Constructor for Expr * @throws Z3Exception on error **/ protected Expr(Context ctx, long obj) { super(ctx, obj); Type superclass = getClass().getGenericSuperclass(); if (superclass instanceof ParameterizedType) { Type argType = ((ParameterizedType) superclass).getActualTypeArguments()[0]; if (argType instanceof Class) { this.sort = (Class) argType; } } } @Override void checkNativeObject(long obj) { if (!Native.isApp(getContext().nCtx(), obj) && Native.getAstKind(getContext().nCtx(), obj) != Z3_ast_kind.Z3_VAR_AST.toInt() && Native.getAstKind(getContext().nCtx(), obj) != Z3_ast_kind.Z3_QUANTIFIER_AST.toInt()) { throw new Z3Exception("Underlying object is not a term"); } super.checkNativeObject(obj); } static <U extends Sort> Expr<U> create(Context ctx, FuncDecl<U> f, Expr<?> ... arguments) { long obj = Native.mkApp(ctx.nCtx(), f.getNativeObject(), AST.arrayLength(arguments), AST.arrayToNative(arguments)); return (Expr<U>) create(ctx, obj); } // TODO generify, but it conflicts with AST.create static Expr<?> create(Context ctx, long obj) { Z3_ast_kind k = Z3_ast_kind.fromInt(Native.getAstKind(ctx.nCtx(), obj)); if (k == Z3_ast_kind.Z3_QUANTIFIER_AST) return new Quantifier(ctx, obj); long s = Native.getSort(ctx.nCtx(), obj); Z3_sort_kind sk = Z3_sort_kind .fromInt(Native.getSortKind(ctx.nCtx(), s)); if (Native.isAlgebraicNumber(ctx.nCtx(), obj)) // is this a numeral ast? return new AlgebraicNum(ctx, obj); if (Native.isNumeralAst(ctx.nCtx(), obj)) { switch (sk) { case Z3_INT_SORT: return new IntNum(ctx, obj); case Z3_REAL_SORT: return new RatNum(ctx, obj); case Z3_BV_SORT: return new BitVecNum(ctx, obj); case Z3_FLOATING_POINT_SORT: return new FPNum(ctx, obj); case Z3_ROUNDING_MODE_SORT: return new FPRMNum(ctx, obj); case Z3_FINITE_DOMAIN_SORT: return new FiniteDomainNum(ctx, obj); default: } } switch (sk) { case Z3_BOOL_SORT: return new BoolExpr(ctx, obj); case Z3_INT_SORT: return new IntExpr(ctx, obj); case Z3_REAL_SORT: return new RealExpr(ctx, obj); case Z3_BV_SORT: return new BitVecExpr(ctx, obj); case Z3_ARRAY_SORT: return new ArrayExpr<>(ctx, obj); case Z3_DATATYPE_SORT: return new DatatypeExpr<>(ctx, obj); case Z3_FLOATING_POINT_SORT: return new FPExpr(ctx, obj); case Z3_ROUNDING_MODE_SORT: return new FPRMExpr(ctx, obj); case Z3_FINITE_DOMAIN_SORT: return new FiniteDomainExpr(ctx, obj); case Z3_SEQ_SORT: return new SeqExpr<>(ctx, obj); case Z3_RE_SORT: return new ReExpr<>(ctx, obj); default: } return new Expr<>(ctx, obj); } }
68,960
30.204072
184
java
z3
z3-master/src/api/java/FPExpr.java
/*++ Copyright (c) 2013 Microsoft Corporation Module Name: FPExpr.java Abstract: Author: Christoph Wintersteiger (cwinter) 2013-06-10 Notes: --*/ package com.microsoft.z3; /** * FloatingPoint Expressions */ public class FPExpr extends Expr<FPSort> { /** * The number of exponent bits. * @throws Z3Exception */ public int getEBits() { return ((FPSort)getSort()).getEBits(); } /** * The number of significand bits. * @throws Z3Exception */ public int getSBits() { return ((FPSort)getSort()).getSBits(); } public FPExpr(Context ctx, long obj) { super(ctx, obj); } }
664
14.833333
68
java
z3
z3-master/src/api/java/FPNum.java
/*++ Copyright (c) 2013 Microsoft Corporation Module Name: FPNum.java Abstract: Author: Christoph Wintersteiger (cwinter) 2013-06-10 Notes: --*/ package com.microsoft.z3; /** * FloatingPoint Numerals */ public class FPNum extends FPExpr { /** * Retrieves the sign of a floating-point literal * Remarks: returns true if the numeral is negative * @throws Z3Exception */ public boolean getSign() { Native.IntPtr res = new Native.IntPtr(); if (!Native.fpaGetNumeralSign(getContext().nCtx(), getNativeObject(), res)) throw new Z3Exception("Sign is not a Boolean value"); return res.value != 0; } /** * The sign of a floating-point numeral as a bit-vector expression * Remarks: NaN's do not have a bit-vector sign, so they are invalid arguments. * @throws Z3Exception */ public BitVecExpr getSignBV() { return new BitVecExpr(getContext(), Native.fpaGetNumeralSignBv(getContext().nCtx(), getNativeObject())); } /** * The significand value of a floating-point numeral as a string * Remarks: The significand s is always 0 &lt; s &lt; 2.0; the resulting string is long * enough to represent the real significand precisely. * @throws Z3Exception **/ public String getSignificand() { return Native.fpaGetNumeralSignificandString(getContext().nCtx(), getNativeObject()); } /** * The significand value of a floating-point numeral as a UInt64 * Remarks: This function extracts the significand bits, without the * hidden bit or normalization. Throws an exception if the * significand does not fit into a UInt64. * @throws Z3Exception **/ public long getSignificandUInt64() { Native.LongPtr res = new Native.LongPtr(); if (!Native.fpaGetNumeralSignificandUint64(getContext().nCtx(), getNativeObject(), res)) throw new Z3Exception("Significand is not a 64 bit unsigned integer"); return res.value; } /** * The significand of a floating-point numeral as a bit-vector expression * Remarks: NaN is an invalid argument. * @throws Z3Exception */ public BitVecExpr getSignificandBV() { return new BitVecExpr(getContext(), Native.fpaGetNumeralSignificandBv(getContext().nCtx(), getNativeObject())); } /** * Return the exponent value of a floating-point numeral as a string * Remarks: NaN is an invalid argument. * @throws Z3Exception */ public String getExponent(boolean biased) { return Native.fpaGetNumeralExponentString(getContext().nCtx(), getNativeObject(), biased); } /** * Return the exponent value of a floating-point numeral as a signed 64-bit integer * Remarks: NaN is an invalid argument. * @throws Z3Exception */ public long getExponentInt64(boolean biased) { Native.LongPtr res = new Native.LongPtr(); if (!Native.fpaGetNumeralExponentInt64(getContext().nCtx(), getNativeObject(), res, biased)) throw new Z3Exception("Exponent is not a 64 bit integer"); return res.value; } /** * The exponent of a floating-point numeral as a bit-vector expression * Remarks: NaN is an invalid argument. * @throws Z3Exception */ public BitVecExpr getExponentBV(boolean biased) { return new BitVecExpr(getContext(), Native.fpaGetNumeralExponentBv(getContext().nCtx(), getNativeObject(), biased)); } /** * Indicates whether the numeral is a NaN. * @throws Z3Exception on error * @return a boolean **/ public boolean isNaN() { return Native.fpaIsNumeralNan(getContext().nCtx(), getNativeObject()); } /** * Indicates whether the numeral is a +oo or -oo. * @throws Z3Exception on error * @return a boolean **/ public boolean isInf() { return Native.fpaIsNumeralInf(getContext().nCtx(), getNativeObject()); } /** * Indicates whether the numeral is +zero or -zero. * @throws Z3Exception on error * @return a boolean **/ public boolean isZero() { return Native.fpaIsNumeralZero(getContext().nCtx(), getNativeObject()); } /** * Indicates whether the numeral is normal. * @throws Z3Exception on error * @return a boolean **/ public boolean isNormal() { return Native.fpaIsNumeralNormal(getContext().nCtx(), getNativeObject()); } /** * Indicates whether the numeral is subnormal. * @throws Z3Exception on error * @return a boolean **/ public boolean isSubnormal() { return Native.fpaIsNumeralSubnormal(getContext().nCtx(), getNativeObject()); } /** * Indicates whether the numeral is positive. * @throws Z3Exception on error * @return a boolean **/ public boolean isPositive() { return Native.fpaIsNumeralPositive(getContext().nCtx(), getNativeObject()); } /** * Indicates whether the numeral is negative. * @throws Z3Exception on error * @return a boolean **/ public boolean isNegative() { return Native.fpaIsNumeralNegative(getContext().nCtx(), getNativeObject()); } public FPNum(Context ctx, long obj) { super(ctx, obj); } /** * Returns a string representation of the numeral. */ public String toString() { return Native.getNumeralString(getContext().nCtx(), getNativeObject()); } }
5,633
28.041237
124
java
z3
z3-master/src/api/java/FPRMExpr.java
/*++ Copyright (c) 2013 Microsoft Corporation Module Name: FPRMExpr.java Abstract: Author: Christoph Wintersteiger (cwinter) 2013-06-10 Notes: --*/ package com.microsoft.z3; /** * FloatingPoint RoundingMode Expressions */ public class FPRMExpr extends Expr<FPRMSort> { public FPRMExpr(Context ctx, long obj) { super(ctx, obj); } }
381
11.733333
48
java
z3
z3-master/src/api/java/FPRMNum.java
/*++ Copyright (c) 2013 Microsoft Corporation Module Name: FPRMNum.java Abstract: Author: Christoph Wintersteiger (cwinter) 2013-06-10 Notes: --*/ package com.microsoft.z3; import com.microsoft.z3.enumerations.Z3_decl_kind; /** * FloatingPoint RoundingMode Numerals */ public class FPRMNum extends FPRMExpr { /** * Indicates whether the term is the floating-point rounding numeral roundNearestTiesToEven * @throws Z3Exception * **/ public boolean isRoundNearestTiesToEven() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN; } /** * Indicates whether the term is the floating-point rounding numeral roundNearestTiesToEven * @throws Z3Exception */ public boolean isRNE() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN; } /** * Indicates whether the term is the floating-point rounding numeral roundNearestTiesToAway * @throws Z3Exception */ public boolean isRoundNearestTiesToAway() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY; } /** * Indicates whether the term is the floating-point rounding numeral roundNearestTiesToAway * @throws Z3Exception */ public boolean isRNA() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY; } /** * Indicates whether the term is the floating-point rounding numeral roundTowardPositive * @throws Z3Exception */ public boolean isRoundTowardPositive() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_FPA_RM_TOWARD_POSITIVE; } /** * Indicates whether the term is the floating-point rounding numeral roundTowardPositive * @throws Z3Exception */ public boolean isRTP() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_FPA_RM_TOWARD_POSITIVE; } /** * Indicates whether the term is the floating-point rounding numeral roundTowardNegative * @throws Z3Exception */ public boolean isRoundTowardNegative() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_FPA_RM_TOWARD_NEGATIVE; } /** * Indicates whether the term is the floating-point rounding numeral roundTowardNegative * @throws Z3Exception */ public boolean isRTN() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_FPA_RM_TOWARD_NEGATIVE; } /** * Indicates whether the term is the floating-point rounding numeral roundTowardZero * @throws Z3Exception */ public boolean isRoundTowardZero() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_FPA_RM_TOWARD_ZERO; } /** * Indicates whether the term is the floating-point rounding numeral roundTowardZero * @throws Z3Exception */ public boolean isRTZ() { return isApp() && getFuncDecl().getDeclKind() == Z3_decl_kind.Z3_OP_FPA_RM_TOWARD_ZERO; } public FPRMNum(Context ctx, long obj) { super(ctx, obj); } }
3,127
33.373626
146
java
z3
z3-master/src/api/java/FPRMSort.java
/*++ Copyright (c) 2013 Microsoft Corporation Module Name: FPRMExpr.java Abstract: Author: Christoph Wintersteiger (cwinter) 2013-06-10 Notes: --*/ package com.microsoft.z3; /** * The FloatingPoint RoundingMode sort **/ public class FPRMSort extends Sort { public FPRMSort(Context ctx) { super(ctx, Native.mkFpaRoundingModeSort(ctx.nCtx())); } public FPRMSort(Context ctx, long obj) { super(ctx, obj); } }
479
12.714286
61
java
z3
z3-master/src/api/java/FPSort.java
/*++ Copyright (c) 2013 Microsoft Corporation Module Name: FPSort.java Abstract: Author: Christoph Wintersteiger (cwinter) 2013-06-10 Notes: --*/ package com.microsoft.z3; /** * A FloatingPoint sort **/ public class FPSort extends Sort { public FPSort(Context ctx, long obj) { super(ctx, obj); } public FPSort(Context ctx, int ebits, int sbits) { super(ctx, Native.mkFpaSort(ctx.nCtx(), ebits, sbits)); } /** * The number of exponent bits. */ public int getEBits() { return Native.fpaGetEbits(getContext().nCtx(), getNativeObject()); } /** * The number of significand bits. */ public int getSBits() { return Native.fpaGetSbits(getContext().nCtx(), getNativeObject()); } }
847
15.96
82
java
z3
z3-master/src/api/java/FiniteDomainExpr.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: FiniteDomainExpr.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2015-12-02 Notes: **/ package com.microsoft.z3; /** * Finite-domain expressions **/ public class FiniteDomainExpr<R> extends Expr<FiniteDomainSort<R>> { /** * Constructor for FiniteDomainExpr * @throws Z3Exception on error **/ FiniteDomainExpr(Context ctx, long obj) { super(ctx, obj); } }
501
13.764706
66
java
z3
z3-master/src/api/java/FiniteDomainNum.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: FiniteDomainNum.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2015-12-02 Notes: **/ package com.microsoft.z3; import java.math.BigInteger; /** * Finite-domain Numerals **/ public class FiniteDomainNum<R> extends FiniteDomainExpr<R> { FiniteDomainNum(Context ctx, long obj) { super(ctx, obj); } /** * Retrieve the int value. **/ public int getInt() { Native.IntPtr res = new Native.IntPtr(); if (!Native.getNumeralInt(getContext().nCtx(), getNativeObject(), res)) { throw new Z3Exception("Numeral is not an int"); } return res.value; } /** * Retrieve the 64-bit int value. **/ public long getInt64() { Native.LongPtr res = new Native.LongPtr(); if (!Native.getNumeralInt64(getContext().nCtx(), getNativeObject(), res)) { throw new Z3Exception("Numeral is not an int64"); } return res.value; } /** * Retrieve the BigInteger value. **/ public BigInteger getBigInteger() { return new BigInteger(this.toString()); } /** * Returns a string representation of the numeral. **/ @Override public String toString() { return Native.getNumeralString(getContext().nCtx(), getNativeObject()); } }
1,429
18.324324
83
java
z3
z3-master/src/api/java/FiniteDomainSort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: FiniteDomainSort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Finite domain sorts. **/ public class FiniteDomainSort<R> extends Sort { /** * The size of the finite domain sort. * @throws Z3Exception on error **/ public long getSize() { Native.LongPtr res = new Native.LongPtr(); Native.getFiniteDomainSortSize(getContext().nCtx(), getNativeObject(), res); return res.value; } FiniteDomainSort(Context ctx, long obj) { super(ctx, obj); } FiniteDomainSort(Context ctx, Symbol name, long size) { super(ctx, Native.mkFiniteDomainSort(ctx.nCtx(), name.getNativeObject(), size)); } }
854
17.191489
84
java
z3
z3-master/src/api/java/Fixedpoint.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Fixedpoint.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import com.microsoft.z3.enumerations.Z3_lbool; /** * Object for managing fixedpoints **/ public class Fixedpoint extends Z3Object { /** * A string that describes all available fixedpoint solver parameters. **/ public String getHelp() { return Native.fixedpointGetHelp(getContext().nCtx(), getNativeObject()); } /** * Sets the fixedpoint solver parameters. * * @throws Z3Exception **/ public void setParameters(Params value) { getContext().checkContextMatch(value); Native.fixedpointSetParams(getContext().nCtx(), getNativeObject(), value.getNativeObject()); } /** * Retrieves parameter descriptions for Fixedpoint solver. * * @throws Z3Exception **/ public ParamDescrs getParameterDescriptions() { return new ParamDescrs(getContext(), Native.fixedpointGetParamDescrs( getContext().nCtx(), getNativeObject())); } /** * Assert a constraint (or multiple) into the fixedpoint solver. * * @throws Z3Exception **/ @SafeVarargs public final void add(Expr<BoolSort>... constraints) { getContext().checkContextMatch(constraints); for (Expr<BoolSort> a : constraints) { Native.fixedpointAssert(getContext().nCtx(), getNativeObject(), a.getNativeObject()); } } /** * Register predicate as recursive relation. * * @throws Z3Exception **/ public void registerRelation(FuncDecl<BoolSort> f) { getContext().checkContextMatch(f); Native.fixedpointRegisterRelation(getContext().nCtx(), getNativeObject(), f.getNativeObject()); } /** * Add rule into the fixedpoint solver. * * @param rule implication (Horn clause) representing rule * @param name Nullable rule name. * @throws Z3Exception **/ public void addRule(Expr<BoolSort> rule, Symbol name) { getContext().checkContextMatch(rule); Native.fixedpointAddRule(getContext().nCtx(), getNativeObject(), rule.getNativeObject(), AST.getNativeObject(name)); } /** * Add table fact to the fixedpoint solver. * * @throws Z3Exception **/ public void addFact(FuncDecl<BoolSort> pred, int ... args) { getContext().checkContextMatch(pred); Native.fixedpointAddFact(getContext().nCtx(), getNativeObject(), pred.getNativeObject(), args.length, args); } /** * Query the fixedpoint solver. A query is a conjunction of constraints. The * constraints may include the recursively defined relations. The query is * satisfiable if there is an instance of the query variables and a * derivation for it. The query is unsatisfiable if there are no derivations * satisfying the query variables. * * @throws Z3Exception **/ public Status query(Expr<BoolSort> query) { getContext().checkContextMatch(query); Z3_lbool r = Z3_lbool.fromInt(Native.fixedpointQuery(getContext().nCtx(), getNativeObject(), query.getNativeObject())); switch (r) { case Z3_L_TRUE: return Status.SATISFIABLE; case Z3_L_FALSE: return Status.UNSATISFIABLE; default: return Status.UNKNOWN; } } /** * Query the fixedpoint solver. A query is an array of relations. The query * is satisfiable if there is an instance of some relation that is * non-empty. The query is unsatisfiable if there are no derivations * satisfying any of the relations. * * @throws Z3Exception **/ public Status query(FuncDecl<BoolSort>[] relations) { getContext().checkContextMatch(relations); Z3_lbool r = Z3_lbool.fromInt(Native.fixedpointQueryRelations(getContext() .nCtx(), getNativeObject(), AST.arrayLength(relations), AST .arrayToNative(relations))); switch (r) { case Z3_L_TRUE: return Status.SATISFIABLE; case Z3_L_FALSE: return Status.UNSATISFIABLE; default: return Status.UNKNOWN; } } /** * Update named rule into in the fixedpoint solver. * * @param rule implication (Horn clause) representing rule * @param name Nullable rule name. * @throws Z3Exception **/ public void updateRule(Expr<BoolSort> rule, Symbol name) { getContext().checkContextMatch(rule); Native.fixedpointUpdateRule(getContext().nCtx(), getNativeObject(), rule.getNativeObject(), AST.getNativeObject(name)); } /** * Retrieve satisfying instance or instances of solver, or definitions for * the recursive predicates that show unsatisfiability. * * @throws Z3Exception **/ public Expr<?> getAnswer() { long ans = Native.fixedpointGetAnswer(getContext().nCtx(), getNativeObject()); return (ans == 0) ? null : Expr.create(getContext(), ans); } /** * Retrieve explanation why fixedpoint engine returned status Unknown. **/ public String getReasonUnknown() { return Native.fixedpointGetReasonUnknown(getContext().nCtx(), getNativeObject()); } /** * Retrieve the number of levels explored for a given predicate. **/ public int getNumLevels(FuncDecl<BoolSort> predicate) { return Native.fixedpointGetNumLevels(getContext().nCtx(), getNativeObject(), predicate.getNativeObject()); } /** * Retrieve the cover of a predicate. * * @throws Z3Exception **/ public Expr<?> getCoverDelta(int level, FuncDecl<BoolSort> predicate) { long res = Native.fixedpointGetCoverDelta(getContext().nCtx(), getNativeObject(), level, predicate.getNativeObject()); return (res == 0) ? null : Expr.create(getContext(), res); } /** * Add <tt>property</tt> about the <tt>predicate</tt>. The property is added * at <tt>level</tt>. **/ public void addCover(int level, FuncDecl<BoolSort> predicate, Expr<?> property) { Native.fixedpointAddCover(getContext().nCtx(), getNativeObject(), level, predicate.getNativeObject(), property.getNativeObject()); } /** * Retrieve internal string representation of fixedpoint object. **/ @Override public String toString() { return Native.fixedpointToString(getContext().nCtx(), getNativeObject(), 0, null); } /** * Instrument the Datalog engine on which table representation to use for * recursive predicate. **/ public void setPredicateRepresentation(FuncDecl<BoolSort> f, Symbol[] kinds) { Native.fixedpointSetPredicateRepresentation(getContext().nCtx(), getNativeObject(), f.getNativeObject(), AST.arrayLength(kinds), Symbol.arrayToNative(kinds)); } /** * Convert benchmark given as set of axioms, rules and queries to a string. **/ public String toString(Expr<BoolSort>[] queries) { return Native.fixedpointToString(getContext().nCtx(), getNativeObject(), AST.arrayLength(queries), AST.arrayToNative(queries)); } /** * Retrieve set of rules added to fixedpoint context. * * @throws Z3Exception **/ public BoolExpr[] getRules() { ASTVector v = new ASTVector(getContext(), Native.fixedpointGetRules(getContext().nCtx(), getNativeObject())); return v.ToBoolExprArray(); } /** * Retrieve set of assertions added to fixedpoint context. * * @throws Z3Exception **/ public BoolExpr[] getAssertions() { ASTVector v = new ASTVector(getContext(), Native.fixedpointGetAssertions(getContext().nCtx(), getNativeObject())); return v.ToBoolExprArray(); } /** * Fixedpoint statistics. * * @throws Z3Exception **/ public Statistics getStatistics() { return new Statistics(getContext(), Native.fixedpointGetStatistics( getContext().nCtx(), getNativeObject())); } /** * Parse an SMT-LIB2 file with fixedpoint rules. * Add the rules to the current fixedpoint context. * Return the set of queries in the file. **/ public BoolExpr[] ParseFile(String file) { ASTVector av = new ASTVector(getContext(), Native.fixedpointFromFile(getContext().nCtx(), getNativeObject(), file)); return av.ToBoolExprArray(); } /** * Parse an SMT-LIB2 string with fixedpoint rules. * Add the rules to the current fixedpoint context. * Return the set of queries in the file. **/ public BoolExpr[] ParseString(String s) { ASTVector av = new ASTVector(getContext(), Native.fixedpointFromString(getContext().nCtx(), getNativeObject(), s)); return av.ToBoolExprArray(); } Fixedpoint(Context ctx, long obj) throws Z3Exception { super(ctx, obj); } Fixedpoint(Context ctx) { super(ctx, Native.mkFixedpoint(ctx.nCtx())); } @Override void incRef() { Native.fixedpointIncRef(getContext().nCtx(), getNativeObject()); } @Override void addToReferenceQueue() { getContext().getFixedpointDRQ().storeReference(getContext(), this); } @Override void checkNativeObject(long obj) { } }
9,854
28.330357
124
java
z3
z3-master/src/api/java/FixedpointDecRefQueue.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: FixedpointDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; class FixedpointDecRefQueue extends IDecRefQueue<Fixedpoint> { public FixedpointDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.fixedpointDecRef(ctx.nCtx(), obj); } };
480
14.03125
62
java
z3
z3-master/src/api/java/FuncDecl.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: FuncDecl.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import com.microsoft.z3.enumerations.Z3_ast_kind; import com.microsoft.z3.enumerations.Z3_decl_kind; import com.microsoft.z3.enumerations.Z3_parameter_kind; /** * Function declarations. **/ public class FuncDecl<R extends Sort> extends AST { /** * Object comparison. **/ @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof FuncDecl)) return false; FuncDecl<?> other = (FuncDecl<?>) o; return (getContext().nCtx() == other.getContext().nCtx()) && (Native.isEqFuncDecl( getContext().nCtx(), getNativeObject(), other.getNativeObject())); } @Override public String toString() { return Native.funcDeclToString(getContext().nCtx(), getNativeObject()); } /** * Returns a unique identifier for the function declaration. **/ @Override public int getId() { return Native.getFuncDeclId(getContext().nCtx(), getNativeObject()); } /** * Translates (copies) the function declaration to the Context {@code ctx}. * @param ctx A context * * @return A copy of the function declaration which is associated with {@code ctx} * @throws Z3Exception on error **/ @SuppressWarnings("unchecked") public FuncDecl<R> translate(Context ctx) { return (FuncDecl<R>) super.translate(ctx); } /** * The arity of the function declaration **/ public int getArity() { return Native.getArity(getContext().nCtx(), getNativeObject()); } /** * The size of the domain of the function declaration * @see #getArity **/ public int getDomainSize() { return Native.getDomainSize(getContext().nCtx(), getNativeObject()); } /** * The domain of the function declaration **/ public Sort[] getDomain() { int n = getDomainSize(); Sort[] res = new Sort[n]; for (int i = 0; i < n; i++) res[i] = Sort.create(getContext(), Native.getDomain(getContext().nCtx(), getNativeObject(), i)); return res; } /** * The range of the function declaration **/ @SuppressWarnings("unchecked") public R getRange() { return (R) Sort.create(getContext(), Native.getRange(getContext().nCtx(), getNativeObject())); } /** * The kind of the function declaration. **/ public Z3_decl_kind getDeclKind() { return Z3_decl_kind.fromInt(Native.getDeclKind(getContext().nCtx(), getNativeObject())); } /** * The name of the function declaration **/ public Symbol getName() { return Symbol.create(getContext(), Native.getDeclName(getContext().nCtx(), getNativeObject())); } /** * The number of parameters of the function declaration **/ public int getNumParameters() { return Native.getDeclNumParameters(getContext().nCtx(), getNativeObject()); } /** * The parameters of the function declaration **/ public Parameter[] getParameters() { int num = getNumParameters(); Parameter[] res = new Parameter[num]; for (int i = 0; i < num; i++) { Z3_parameter_kind k = Z3_parameter_kind.fromInt(Native .getDeclParameterKind(getContext().nCtx(), getNativeObject(), i)); switch (k) { case Z3_PARAMETER_INT: res[i] = new Parameter(k, Native.getDeclIntParameter(getContext() .nCtx(), getNativeObject(), i)); break; case Z3_PARAMETER_DOUBLE: res[i] = new Parameter(k, Native.getDeclDoubleParameter( getContext().nCtx(), getNativeObject(), i)); break; case Z3_PARAMETER_SYMBOL: res[i] = new Parameter(k, Symbol.create(getContext(), Native .getDeclSymbolParameter(getContext().nCtx(), getNativeObject(), i))); break; case Z3_PARAMETER_SORT: res[i] = new Parameter(k, Sort.create(getContext(), Native .getDeclSortParameter(getContext().nCtx(), getNativeObject(), i))); break; case Z3_PARAMETER_AST: res[i] = new Parameter(k, new AST(getContext(), Native.getDeclAstParameter(getContext().nCtx(), getNativeObject(), i))); break; case Z3_PARAMETER_FUNC_DECL: res[i] = new Parameter(k, new FuncDecl<>(getContext(), Native.getDeclFuncDeclParameter(getContext().nCtx(), getNativeObject(), i))); break; case Z3_PARAMETER_RATIONAL: res[i] = new Parameter(k, Native.getDeclRationalParameter( getContext().nCtx(), getNativeObject(), i)); break; default: throw new Z3Exception( "Unknown function declaration parameter kind encountered"); } } return res; } /** * Function declarations can have Parameters associated with them. **/ public static class Parameter { private Z3_parameter_kind kind; private int i; private double d; private Symbol sym; private Sort srt; private AST ast; private FuncDecl<?> fd; private String r; /** * The int value of the parameter. **/ public int getInt() { if (getParameterKind() != Z3_parameter_kind.Z3_PARAMETER_INT) throw new Z3Exception("parameter is not an int"); return i; } /** * The double value of the parameter. **/ public double getDouble() { if (getParameterKind() != Z3_parameter_kind.Z3_PARAMETER_DOUBLE) throw new Z3Exception("parameter is not a double "); return d; } /** * The Symbol value of the parameter. **/ public Symbol getSymbol() { if (getParameterKind() != Z3_parameter_kind.Z3_PARAMETER_SYMBOL) throw new Z3Exception("parameter is not a Symbol"); return sym; } /** * The Sort value of the parameter. **/ public Sort getSort() { if (getParameterKind() != Z3_parameter_kind.Z3_PARAMETER_SORT) throw new Z3Exception("parameter is not a Sort"); return srt; } /** * The AST value of the parameter. **/ public AST getAST() { if (getParameterKind() != Z3_parameter_kind.Z3_PARAMETER_AST) throw new Z3Exception("parameter is not an AST"); return ast; } /** * The FunctionDeclaration value of the parameter. **/ public FuncDecl<?> getFuncDecl() { if (getParameterKind() != Z3_parameter_kind.Z3_PARAMETER_FUNC_DECL) throw new Z3Exception("parameter is not a function declaration"); return fd; } /** * The rational string value of the parameter. **/ public String getRational() { if (getParameterKind() != Z3_parameter_kind.Z3_PARAMETER_RATIONAL) throw new Z3Exception("parameter is not a rational String"); return r; } /** * The kind of the parameter. **/ public Z3_parameter_kind getParameterKind() { return kind; } Parameter(Z3_parameter_kind k, int i) { this.kind = k; this.i = i; } Parameter(Z3_parameter_kind k, double d) { this.kind = k; this.d = d; } Parameter(Z3_parameter_kind k, Symbol s) { this.kind = k; this.sym = s; } Parameter(Z3_parameter_kind k, Sort s) { this.kind = k; this.srt = s; } Parameter(Z3_parameter_kind k, AST a) { this.kind = k; this.ast = a; } Parameter(Z3_parameter_kind k, FuncDecl<?> fd) { this.kind = k; this.fd = fd; } Parameter(Z3_parameter_kind k, String r) { this.kind = k; this.r = r; } } FuncDecl(Context ctx, long obj) { super(ctx, obj); } FuncDecl(Context ctx, Symbol name, Sort[] domain, R range) { super(ctx, Native.mkFuncDecl(ctx.nCtx(), name.getNativeObject(), AST.arrayLength(domain), AST.arrayToNative(domain), range.getNativeObject())); } FuncDecl(Context ctx, Symbol name, Sort[] domain, R range, boolean is_rec) { super(ctx, Native.mkRecFuncDecl(ctx.nCtx(), name.getNativeObject(), AST.arrayLength(domain), AST.arrayToNative(domain), range.getNativeObject())); } FuncDecl(Context ctx, String prefix, Sort[] domain, R range) { super(ctx, Native.mkFreshFuncDecl(ctx.nCtx(), prefix, AST.arrayLength(domain), AST.arrayToNative(domain), range.getNativeObject())); } void checkNativeObject(long obj) { if (Native.getAstKind(getContext().nCtx(), obj) != Z3_ast_kind.Z3_FUNC_DECL_AST .toInt()) throw new Z3Exception( "Underlying object is not a function declaration"); super.checkNativeObject(obj); } /** * Create expression that applies function to arguments. **/ public Expr<R> apply(Expr<?> ... args) { getContext().checkContextMatch(args); return Expr.create(getContext(), this, args); } }
10,469
26.552632
87
java
z3
z3-master/src/api/java/FuncInterp.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: FuncInterp.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * A function interpretation is represented as a finite map and an 'else' value. * Each entry in the finite map represents the value of a function given a set * of arguments. **/ @SuppressWarnings("unchecked") public class FuncInterp<R extends Sort> extends Z3Object { /** * An Entry object represents an element in the finite map used to encode a * function interpretation. **/ public static class Entry<R extends Sort> extends Z3Object { /** * Return the (symbolic) value of this entry. * * @throws Z3Exception * @throws Z3Exception on error **/ public Expr<R> getValue() { return (Expr<R>) Expr.create(getContext(), Native.funcEntryGetValue(getContext().nCtx(), getNativeObject())); } /** * The number of arguments of the entry. * @throws Z3Exception on error **/ public int getNumArgs() { return Native.funcEntryGetNumArgs(getContext().nCtx(), getNativeObject()); } /** * The arguments of the function entry. * * @throws Z3Exception * @throws Z3Exception on error **/ public Expr<?>[] getArgs() { int n = getNumArgs(); Expr<?>[] res = new Expr[n]; for (int i = 0; i < n; i++) res[i] = Expr.create(getContext(), Native.funcEntryGetArg( getContext().nCtx(), getNativeObject(), i)); return res; } /** * A string representation of the function entry. **/ @Override public String toString() { int n = getNumArgs(); String res = "["; Expr<?>[] args = getArgs(); for (int i = 0; i < n; i++) res += args[i] + ", "; return res + getValue() + "]"; } Entry(Context ctx, long obj) { super(ctx, obj); } @Override void incRef() { Native.funcEntryIncRef(getContext().nCtx(), getNativeObject()); } @Override void addToReferenceQueue() { getContext().getFuncEntryDRQ().storeReference(getContext(), this); } } /** * The number of entries in the function interpretation. * @throws Z3Exception on error * @return an int **/ public int getNumEntries() { return Native.funcInterpGetNumEntries(getContext().nCtx(), getNativeObject()); } /** * The entries in the function interpretation * * @throws Z3Exception * @throws Z3Exception on error **/ public Entry<R>[] getEntries() { int n = getNumEntries(); Entry<R>[] res = new Entry[n]; for (int i = 0; i < n; i++) res[i] = new Entry<>(getContext(), Native.funcInterpGetEntry(getContext() .nCtx(), getNativeObject(), i)); return res; } /** * The (symbolic) `else' value of the function interpretation. * * @throws Z3Exception * @throws Z3Exception on error * @return an Expr **/ public Expr<R> getElse() { return (Expr<R>) Expr.create(getContext(), Native.funcInterpGetElse(getContext().nCtx(), getNativeObject())); } /** * The arity of the function interpretation * @throws Z3Exception on error * @return an int **/ public int getArity() { return Native.funcInterpGetArity(getContext().nCtx(), getNativeObject()); } /** * A string representation of the function interpretation. **/ public String toString() { String res = ""; res += "["; for (Entry<R> e : getEntries()) { int n = e.getNumArgs(); if (n > 1) res += "["; Expr<?>[] args = e.getArgs(); for (int i = 0; i < n; i++) { if (i != 0) res += ", "; res += args[i]; } if (n > 1) res += "]"; res += " -> " + e.getValue() + ", "; } res += "else -> " + getElse(); res += "]"; return res; } FuncInterp(Context ctx, long obj) { super(ctx, obj); } @Override void incRef() { Native.funcInterpIncRef(getContext().nCtx(), getNativeObject()); } @Override void addToReferenceQueue() { getContext().getFuncInterpDRQ().storeReference(getContext(), this); } }
4,865
24.34375
86
java
z3
z3-master/src/api/java/FuncInterpDecRefQueue.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: FuncInterpDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; class FuncInterpDecRefQueue extends IDecRefQueue<FuncInterp<?>> { public FuncInterpDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.funcInterpDecRef(ctx.nCtx(), obj); } };
479
14
63
java
z3
z3-master/src/api/java/FuncInterpEntryDecRefQueue.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: FuncInterpEntryDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; class FuncInterpEntryDecRefQueue extends IDecRefQueue<FuncInterp.Entry<?>> { public FuncInterpEntryDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.funcEntryDecRef(ctx.nCtx(), obj); } }
497
15.064516
76
java
z3
z3-master/src/api/java/Global.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Global.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Global functions for Z3. * Remarks: * This (static) class contains functions that effect the behaviour of Z3 * globally across contexts, etc. * **/ public final class Global { /** * Set a global (or module) parameter, which is shared by all Z3 contexts. * Remarks: * When a Z3 module is initialized it will use the value of these parameters * when Z3_params objects are not provided. * The name of parameter can be composed of characters [a-z][A-Z], digits [0-9], '-' and '_'. * The character '.' is a delimiter (more later). * The parameter names are case-insensitive. The character '-' should be viewed as an "alias" for '_'. * Thus, the following parameter names are considered equivalent: "pp.decimal-precision" and "PP.DECIMAL_PRECISION". * This function can be used to set parameters for a specific Z3 module. * This can be done by using &lt;module-name&gt;.&lt;parameter-name&gt;. * For example: * Z3_global_param_set('pp.decimal', 'true') * will set the parameter "decimal" in the module "pp" to true. * **/ public static void setParameter(String id, String value) { Native.globalParamSet(id, value); } /** * Get a global (or module) parameter. * Remarks: * This function cannot be invoked simultaneously from different threads without synchronization. * The result string stored in param_value is stored in a shared location. * @return null if the parameter {@code id} does not exist. **/ public static String getParameter(String id) { Native.StringPtr res = new Native.StringPtr(); if (!Native.globalParamGet(id, res)) { return null; } else { return res.value; } } /** * Restore the value of all global (and module) parameters. * Remarks: * This command will not affect already created objects (such as tactics and solvers) * @see #setParameter **/ public static void resetParameters() { Native.globalParamResetAll(); } /** * Enable/disable printing of warning messages to the console. * Remarks: Note * that this function is static and effects the behaviour of all contexts * globally. **/ public static void ToggleWarningMessages(boolean enabled) { Native.toggleWarningMessages((enabled)); } /** * Enable tracing messages tagged as `tag' when Z3 is compiled in debug mode. * * Remarks: It is a NOOP otherwise. **/ public static void enableTrace(String tag) { Native.enableTrace(tag); } /** * Disable tracing messages tagged as `tag' when Z3 is compiled in debug mode. * * Remarks: It is a NOOP otherwise. **/ public static void disableTrace(String tag) { Native.disableTrace(tag); } }
3,180
27.918182
121
java
z3
z3-master/src/api/java/Goal.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Goal.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import com.microsoft.z3.enumerations.Z3_goal_prec; /** * A goal (aka problem). A goal is essentially a set of formulas, that can be * solved and/or transformed using tactics and solvers. **/ public class Goal extends Z3Object { /** * The precision of the goal. * Remarks: Goals can be transformed using over * and under approximations. An under approximation is applied when the * objective is to find a model for a given goal. An over approximation is * applied when the objective is to find a proof for a given goal. * **/ public Z3_goal_prec getPrecision() { return Z3_goal_prec.fromInt(Native.goalPrecision(getContext().nCtx(), getNativeObject())); } /** * Indicates whether the goal is precise. **/ public boolean isPrecise() { return getPrecision() == Z3_goal_prec.Z3_GOAL_PRECISE; } /** * Indicates whether the goal is an under-approximation. **/ public boolean isUnderApproximation() { return getPrecision() == Z3_goal_prec.Z3_GOAL_UNDER; } /** * Indicates whether the goal is an over-approximation. **/ public boolean isOverApproximation() { return getPrecision() == Z3_goal_prec.Z3_GOAL_OVER; } /** * Indicates whether the goal is garbage (i.e., the product of over- and * under-approximations). **/ public boolean isGarbage() { return getPrecision() == Z3_goal_prec.Z3_GOAL_UNDER_OVER; } /** * Adds the {@code constraints} to the given goal. * * @throws Z3Exception **/ @SafeVarargs public final void add(Expr<BoolSort>... constraints) { getContext().checkContextMatch(constraints); for (Expr<BoolSort> c : constraints) { Native.goalAssert(getContext().nCtx(), getNativeObject(), c.getNativeObject()); } } /** * Indicates whether the goal contains `false'. **/ public boolean inconsistent() { return Native.goalInconsistent(getContext().nCtx(), getNativeObject()); } /** * The depth of the goal. * Remarks: This tracks how many transformations * were applied to it. **/ public int getDepth() { return Native.goalDepth(getContext().nCtx(), getNativeObject()); } /** * Erases all formulas from the given goal. **/ public void reset() { Native.goalReset(getContext().nCtx(), getNativeObject()); } /** * The number of formulas in the goal. **/ public int size() { return Native.goalSize(getContext().nCtx(), getNativeObject()); } /** * The formulas in the goal. * * @throws Z3Exception **/ public BoolExpr[] getFormulas() { int n = size(); BoolExpr[] res = new BoolExpr[n]; for (int i = 0; i < n; i++) res[i] = (BoolExpr) Expr.create(getContext(), Native.goalFormula(getContext().nCtx(), getNativeObject(), i)); return res; } /** * The number of formulas, subformulas and terms in the goal. **/ public int getNumExprs() { return Native.goalNumExprs(getContext().nCtx(), getNativeObject()); } /** * Indicates whether the goal is empty, and it is precise or the product of * an under approximation. **/ public boolean isDecidedSat() { return Native.goalIsDecidedSat(getContext().nCtx(), getNativeObject()); } /** * Indicates whether the goal contains `false', and it is precise or the * product of an over approximation. **/ public boolean isDecidedUnsat() { return Native .goalIsDecidedUnsat(getContext().nCtx(), getNativeObject()); } /** * Translates (copies) the Goal to the target Context {@code ctx}. * * @throws Z3Exception **/ public Goal translate(Context ctx) { return new Goal(ctx, Native.goalTranslate(getContext().nCtx(), getNativeObject(), ctx.nCtx())); } /** * Simplifies the goal. * Remarks: Essentially invokes the `simplify' tactic * on the goal. **/ public Goal simplify() { Tactic t = getContext().mkTactic("simplify"); ApplyResult res = t.apply(this); if (res.getNumSubgoals() == 0) throw new Z3Exception("No subgoals"); else return res.getSubgoals()[0]; } /** * Simplifies the goal. * Remarks: Essentially invokes the `simplify' tactic * on the goal. **/ public Goal simplify(Params p) { Tactic t = getContext().mkTactic("simplify"); ApplyResult res = t.apply(this, p); if (res.getNumSubgoals() == 0) throw new Z3Exception("No subgoals"); else return res.getSubgoals()[0]; } /** * Goal to string conversion. * * @return A string representation of the Goal. **/ public String toString() { return Native.goalToString(getContext().nCtx(), getNativeObject()); } /** * Goal to BoolExpr conversion. * * Returns a string representation of the Goal. **/ public BoolExpr AsBoolExpr() { int n = size(); if (n == 0) { return getContext().mkTrue(); } else if (n == 1) { return getFormulas()[0]; } else { return getContext().mkAnd(getFormulas()); } } Goal(Context ctx, long obj) { super(ctx, obj); } Goal(Context ctx, boolean models, boolean unsatCores, boolean proofs) { super(ctx, Native.mkGoal(ctx.nCtx(), (models), (unsatCores), (proofs))); } /** * Convert a model for the goal into a model of the * original goal from which this goal was derived. * * @return A model for {@code g} * @throws Z3Exception **/ public Model convertModel(Model m) { return new Model(getContext(), Native.goalConvertModel(getContext().nCtx(), getNativeObject(), m.getNativeObject())); } @Override void incRef() { Native.goalIncRef(getContext().nCtx(), getNativeObject()); } @Override void addToReferenceQueue() { getContext().getGoalDRQ().storeReference(getContext(), this); } }
6,652
23.824627
121
java
z3
z3-master/src/api/java/GoalDecRefQueue.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: GoalDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; class GoalDecRefQueue extends IDecRefQueue<Goal> { public GoalDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.goalDecRef(ctx.nCtx(), obj); } }
449
13.516129
56
java
z3
z3-master/src/api/java/IDecRefQueue.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: IDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import java.lang.ref.PhantomReference; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.util.IdentityHashMap; import java.util.Map; /** * A queue to handle management of native memory. * * <p><b>Mechanics: </b>once an object is created, a metadata is stored for it in * {@code referenceMap}, and a {@link PhantomReference} is created with a * reference to {@code referenceQueue}. * Once the object becomes strongly unreachable, the phantom reference gets * added by JVM to the {@code referenceQueue}. * After each object creation, we iterate through the available objects in * {@code referenceQueue} and decrement references for them. * * @param <T> Type of object stored in queue. */ public abstract class IDecRefQueue<T extends Z3Object> { private final ReferenceQueue<T> referenceQueue = new ReferenceQueue<>(); private final Map<PhantomReference<T>, Long> referenceMap = new IdentityHashMap<>(); protected IDecRefQueue() {} /** * An implementation of this method should decrement the reference on a * given native object. * This function should always be called on the {@code ctx} thread. * * @param ctx Z3 context. * @param obj Pointer to a Z3 object. */ protected abstract void decRef(Context ctx, long obj); public void storeReference(Context ctx, T obj) { PhantomReference<T> ref = new PhantomReference<>(obj, referenceQueue); referenceMap.put(ref, obj.getNativeObject()); clear(ctx); } /** * Clean all references currently in {@code referenceQueue}. */ protected void clear(Context ctx) { Reference<? extends T> ref; while ((ref = referenceQueue.poll()) != null) { long z3ast = referenceMap.remove(ref); decRef(ctx, z3ast); } } /** * Clean all references stored in {@code referenceMap}, * <b>regardless</b> of whether they are in {@code referenceMap} or not. */ public void forceClear(Context ctx) { for (long ref : referenceMap.values()) { decRef(ctx, ref); } } }
2,365
27.166667
81
java
z3
z3-master/src/api/java/IntExpr.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: IntExpr.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Int expressions **/ public class IntExpr extends ArithExpr<IntSort> { /** * Constructor for IntExpr * @throws Z3Exception on error **/ IntExpr(Context ctx, long obj) { super(ctx, obj); } }
445
12.117647
56
java
z3
z3-master/src/api/java/IntNum.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: IntNum.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import java.math.BigInteger; /** * Integer Numerals **/ public class IntNum extends IntExpr { IntNum(Context ctx, long obj) { super(ctx, obj); } /** * Retrieve the int value. **/ public int getInt() { Native.IntPtr res = new Native.IntPtr(); if (!Native.getNumeralInt(getContext().nCtx(), getNativeObject(), res)) throw new Z3Exception("Numeral is not an int"); return res.value; } /** * Retrieve the 64-bit int value. **/ public long getInt64() { Native.LongPtr res = new Native.LongPtr(); if (!Native.getNumeralInt64(getContext().nCtx(), getNativeObject(), res)) throw new Z3Exception("Numeral is not an int64"); return res.value; } /** * Retrieve the BigInteger value. **/ public BigInteger getBigInteger() { return new BigInteger(this.toString()); } /** * Returns a string representation of the numeral. **/ public String toString() { return Native.getNumeralString(getContext().nCtx(), getNativeObject()); } }
1,339
18.142857
81
java
z3
z3-master/src/api/java/IntSort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: IntSort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * An Integer sort **/ public class IntSort extends ArithSort { IntSort(Context ctx, long obj) { super(ctx, obj); } IntSort(Context ctx) { super(ctx, Native.mkIntSort(ctx.nCtx())); } }
440
11.6
56
java
z3
z3-master/src/api/java/IntSymbol.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: IntSymbol.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import com.microsoft.z3.enumerations.Z3_symbol_kind; /** * Numbered symbols **/ public class IntSymbol extends Symbol { /** * The int value of the symbol. * Remarks: Throws an exception if the symbol * is not of int kind. **/ public int getInt() { if (!isIntSymbol()) throw new Z3Exception("Int requested from non-Int symbol"); return Native.getSymbolInt(getContext().nCtx(), getNativeObject()); } IntSymbol(Context ctx, long obj) { super(ctx, obj); } IntSymbol(Context ctx, int i) { super(ctx, Native.mkIntSymbol(ctx.nCtx(), i)); } @Override void checkNativeObject(long obj) { if (Native.getSymbolKind(getContext().nCtx(), obj) != Z3_symbol_kind.Z3_INT_SYMBOL .toInt()) throw new Z3Exception("Symbol is not of integer kind"); super.checkNativeObject(obj); } }
1,143
18.724138
90
java
z3
z3-master/src/api/java/Lambda.java
/** Copyright (c) 2017 Microsoft Corporation Module Name: Lambda.java Abstract: Z3 Java API: Lambda Author: Christoph Wintersteiger (cwinter) 2012-03-19 Notes: **/ package com.microsoft.z3; /** * Lambda expressions. */ public class Lambda<R extends Sort> extends ArrayExpr<Sort, R> { /** * The number of bound variables. **/ public int getNumBound() { return Native.getQuantifierNumBound(getContext().nCtx(), getNativeObject()); } /** * The symbols for the bound variables. * * @throws Z3Exception **/ public Symbol[] getBoundVariableNames() { int n = getNumBound(); Symbol[] res = new Symbol[n]; for (int i = 0; i < n; i++) res[i] = Symbol.create(getContext(), Native.getQuantifierBoundName( getContext().nCtx(), getNativeObject(), i)); return res; } /** * The sorts of the bound variables. * * @throws Z3Exception **/ public Sort[] getBoundVariableSorts() { int n = getNumBound(); Sort[] res = new Sort[n]; for (int i = 0; i < n; i++) res[i] = Sort.create(getContext(), Native.getQuantifierBoundSort( getContext().nCtx(), getNativeObject(), i)); return res; } /** * The body of the quantifier. * * @throws Z3Exception **/ @SuppressWarnings("unchecked") public Expr<R> getBody() { return (Expr<R>) Expr.create(getContext(), Native.getQuantifierBody(getContext() .nCtx(), getNativeObject())); } /** * Translates (copies) the quantifier to the Context {@code ctx}. * * @param ctx A context * * @return A copy of the quantifier which is associated with {@code ctx} * @throws Z3Exception on error **/ public Lambda<R> translate(Context ctx) { return (Lambda<R>) super.translate(ctx); } public static <R extends Sort> Lambda<R> of(Context ctx, Sort[] sorts, Symbol[] names, Expr<R> body) { ctx.checkContextMatch(sorts); ctx.checkContextMatch(names); ctx.checkContextMatch(body); if (sorts.length != names.length) throw new Z3Exception("Number of sorts does not match number of names"); long nativeObject = Native.mkLambda(ctx.nCtx(), AST.arrayLength(sorts), AST.arrayToNative(sorts), Symbol.arrayToNative(names), body.getNativeObject()); return new Lambda<>(ctx, nativeObject); } /** * @param ctx Context to create the lambda on. * @param bound Bound variables. * @param body Body of the lambda expression. */ public static <R extends Sort> Lambda<R> of(Context ctx, Expr<?>[] bound, Expr<R> body) { ctx.checkContextMatch(body); long nativeObject = Native.mkLambdaConst(ctx.nCtx(), AST.arrayLength(bound), AST.arrayToNative(bound), body.getNativeObject()); return new Lambda<>(ctx, nativeObject); } private Lambda(Context ctx, long obj) { super(ctx, obj); } }
3,172
22.503704
104
java
z3
z3-master/src/api/java/ListSort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: ListSort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import com.microsoft.z3.Native.LongPtr; /** * List sorts. **/ public class ListSort<R extends Sort> extends Sort { /** * The declaration of the nil function of this list sort. * @throws Z3Exception **/ public FuncDecl<ListSort<R>> getNilDecl() { return new FuncDecl<>(getContext(), Native.getDatatypeSortConstructor(getContext().nCtx(), getNativeObject(), 0)); } /** * The empty list. * @throws Z3Exception **/ public Expr<ListSort<R>> getNil() { return getContext().mkApp(getNilDecl()); } /** * The declaration of the isNil function of this list sort. * @throws Z3Exception **/ public FuncDecl<BoolSort> getIsNilDecl() { return new FuncDecl<>(getContext(), Native.getDatatypeSortRecognizer(getContext().nCtx(), getNativeObject(), 0)); } /** * The declaration of the cons function of this list sort. * @throws Z3Exception **/ public FuncDecl<ListSort<R>> getConsDecl() { return new FuncDecl<>(getContext(), Native.getDatatypeSortConstructor(getContext().nCtx(), getNativeObject(), 1)); } /** * The declaration of the isCons function of this list sort. * @throws Z3Exception * **/ public FuncDecl<BoolSort> getIsConsDecl() { return new FuncDecl<>(getContext(), Native.getDatatypeSortRecognizer(getContext().nCtx(), getNativeObject(), 1)); } /** * The declaration of the head function of this list sort. * @throws Z3Exception **/ public FuncDecl<R> getHeadDecl() { return new FuncDecl<>(getContext(), Native.getDatatypeSortConstructorAccessor(getContext().nCtx(), getNativeObject(), 1, 0)); } /** * The declaration of the tail function of this list sort. * @throws Z3Exception **/ public FuncDecl<ListSort<R>> getTailDecl() { return new FuncDecl<>(getContext(), Native.getDatatypeSortConstructorAccessor(getContext().nCtx(), getNativeObject(), 1, 1)); } ListSort(Context ctx, Symbol name, Sort elemSort) { super(ctx, Native.mkListSort(ctx.nCtx(), name.getNativeObject(), elemSort.getNativeObject(), new LongPtr(), new Native.LongPtr(), new LongPtr(), new LongPtr(), new LongPtr(), new LongPtr())); } };
2,575
25.020202
133
java
z3
z3-master/src/api/java/Log.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Log.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Interaction logging for Z3. * Remarks: Note that this is a global, static log * and if multiple Context objects are created, it logs the interaction with all * of them. **/ public final class Log { private static boolean m_is_open = false; /** * Open an interaction log file. * @param filename the name of the file to open * * @return True if opening the log file succeeds, false otherwise. **/ public static boolean open(String filename) { m_is_open = true; return Native.openLog(filename) == 1; } /** * Closes the interaction log. **/ public static void close() { m_is_open = false; Native.closeLog(); } /** * Appends the user-provided string {@code s} to the interaction * log. * @throws Z3Exception **/ public static void append(String s) { if (!m_is_open) throw new Z3Exception("Log cannot be closed."); Native.appendLog(s); } /** * Checks whether the interaction log is opened. * * @return True if the interaction log is open, false otherwise. **/ public static boolean isOpen() { return m_is_open; } }
1,450
18.876712
80
java
z3
z3-master/src/api/java/Model.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Model.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import com.microsoft.z3.enumerations.Z3_sort_kind; /** * A Model contains interpretations (assignments) of constants and functions. **/ @SuppressWarnings("unchecked") public class Model extends Z3Object { /** * Retrieves the interpretation (the assignment) of {@code a} in * the model. * @param a A Constant * * @return An expression if the constant has an interpretation in the model, * null otherwise. * @throws Z3Exception **/ public <R extends Sort> Expr<R> getConstInterp(Expr<R> a) { getContext().checkContextMatch(a); return getConstInterp(a.getFuncDecl()); } /** * Retrieves the interpretation (the assignment) of {@code f} in * the model. * @param f A function declaration of zero arity * * @return An expression if the function has an interpretation in the model, * null otherwise. * @throws Z3Exception **/ public <R extends Sort> Expr<R> getConstInterp(FuncDecl<R> f) { getContext().checkContextMatch(f); if (f.getArity() != 0) throw new Z3Exception( "Non-zero arity functions have FunctionInterpretations as a model. Use getFuncInterp."); long n = Native.modelGetConstInterp(getContext().nCtx(), getNativeObject(), f.getNativeObject()); if (n == 0) return null; else return (Expr<R>) Expr.create(getContext(), n); } /** * Retrieves the interpretation (the assignment) of a non-constant {@code f} in the model. * @param f A function declaration of non-zero arity * * @return A FunctionInterpretation if the function has an interpretation in * the model, null otherwise. * @throws Z3Exception **/ public <R extends Sort> FuncInterp<R> getFuncInterp(FuncDecl<R> f) { getContext().checkContextMatch(f); Z3_sort_kind sk = Z3_sort_kind.fromInt(Native.getSortKind(getContext() .nCtx(), Native.getRange(getContext().nCtx(), f.getNativeObject()))); if (f.getArity() == 0) { long n = Native.modelGetConstInterp(getContext().nCtx(), getNativeObject(), f.getNativeObject()); if (sk == Z3_sort_kind.Z3_ARRAY_SORT) { if (n == 0) return null; else { if (Native.isAsArray(getContext().nCtx(), n)) { long fd = Native.getAsArrayFuncDecl(getContext().nCtx(), n); return getFuncInterp(new FuncDecl<>(getContext(), fd)); } return null; } } else { throw new Z3Exception( "Constant functions do not have a function interpretation; use getConstInterp"); } } else { long n = Native.modelGetFuncInterp(getContext().nCtx(), getNativeObject(), f.getNativeObject()); if (n == 0) return null; else return new FuncInterp<>(getContext(), n); } } /** * The number of constants that have an interpretation in the model. **/ public int getNumConsts() { return Native.modelGetNumConsts(getContext().nCtx(), getNativeObject()); } /** * The function declarations of the constants in the model. * * @throws Z3Exception **/ public FuncDecl<?>[] getConstDecls() { int n = getNumConsts(); FuncDecl<?>[] res = new FuncDecl[n]; for (int i = 0; i < n; i++) res[i] = new FuncDecl<>(getContext(), Native.modelGetConstDecl(getContext() .nCtx(), getNativeObject(), i)); return res; } /** * The number of function interpretations in the model. **/ public int getNumFuncs() { return Native.modelGetNumFuncs(getContext().nCtx(), getNativeObject()); } /** * The function declarations of the function interpretations in the model. * * @throws Z3Exception **/ public FuncDecl<?>[] getFuncDecls() { int n = getNumFuncs(); FuncDecl<?>[] res = new FuncDecl[n]; for (int i = 0; i < n; i++) res[i] = new FuncDecl<>(getContext(), Native.modelGetFuncDecl(getContext() .nCtx(), getNativeObject(), i)); return res; } /** * All symbols that have an interpretation in the model. * * @throws Z3Exception **/ public FuncDecl<?>[] getDecls() { int nFuncs = getNumFuncs(); int nConsts = getNumConsts(); int n = nFuncs + nConsts; FuncDecl<?>[] res = new FuncDecl[n]; for (int i = 0; i < nConsts; i++) res[i] = new FuncDecl<>(getContext(), Native.modelGetConstDecl(getContext() .nCtx(), getNativeObject(), i)); for (int i = 0; i < nFuncs; i++) res[nConsts + i] = new FuncDecl<>(getContext(), Native.modelGetFuncDecl( getContext().nCtx(), getNativeObject(), i)); return res; } /** * A ModelEvaluationFailedException is thrown when an expression cannot be * evaluated by the model. **/ @SuppressWarnings("serial") public class ModelEvaluationFailedException extends Z3Exception { /** * An exception that is thrown when model evaluation fails. **/ public ModelEvaluationFailedException() { super(); } } /** * Evaluates the expression {@code t} in the current model. * Remarks: This function may fail if {@code t} contains * quantifiers, is partial (MODEL_PARTIAL enabled), or if {@code t} is not well-sorted. In this case a * {@code ModelEvaluationFailedException} is thrown. * @param t the expression to evaluate * @param completion An expression {@code completion} When this flag * is enabled, a model value will be assigned to any constant or function * that does not have an interpretation in the model. * @return The evaluation of {@code t} in the model. * @throws Z3Exception **/ public <R extends Sort> Expr<R> eval(Expr<R> t, boolean completion) { Native.LongPtr v = new Native.LongPtr(); if (!Native.modelEval(getContext().nCtx(), getNativeObject(), t.getNativeObject(), (completion), v)) throw new ModelEvaluationFailedException(); else return (Expr<R>) Expr.create(getContext(), v.value); } /** * Alias for {@code Eval}. * * @throws Z3Exception **/ public <R extends Sort> Expr<R> evaluate(Expr<R> t, boolean completion) { return eval(t, completion); } /** * The number of uninterpreted sorts that the model has an interpretation * for. **/ public int getNumSorts() { return Native.modelGetNumSorts(getContext().nCtx(), getNativeObject()); } /** * The uninterpreted sorts that the model has an interpretation for. * Remarks: Z3 also provides an interpretation for uninterpreted sorts used * in a formula. The interpretation for a sort is a finite set of distinct * values. We say this finite set is the "universe" of the sort. * * @see #getNumSorts * @see #getSortUniverse(R s) * * @throws Z3Exception **/ public Sort[] getSorts() { int n = getNumSorts(); Sort[] res = new Sort[n]; for (int i = 0; i < n; i++) res[i] = Sort.create(getContext(), Native.modelGetSort(getContext().nCtx(), getNativeObject(), i)); return res; } /** * The finite set of distinct values that represent the interpretation for * sort {@code s}. * @param s An uninterpreted sort * * @return An array of expressions, where each is an element of the universe * of {@code s} * @throws Z3Exception **/ public <R extends Sort> Expr<R>[] getSortUniverse(R s) { ASTVector nUniv = new ASTVector(getContext(), Native.modelGetSortUniverse( getContext().nCtx(), getNativeObject(), s.getNativeObject())); return (Expr<R>[]) nUniv.ToExprArray(); } /** * Conversion of models to strings. * * @return A string representation of the model. **/ @Override public String toString() { return Native.modelToString(getContext().nCtx(), getNativeObject()); } Model(Context ctx, long obj) { super(ctx, obj); } @Override void incRef() { Native.modelIncRef(getContext().nCtx(), getNativeObject()); } @Override void addToReferenceQueue() { getContext().getModelDRQ().storeReference(getContext(), this); } }
9,203
29.476821
108
java
z3
z3-master/src/api/java/ModelDecRefQueue.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: ModelDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; class ModelDecRefQueue extends IDecRefQueue<Model> { public ModelDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.modelDecRef(ctx.nCtx(), obj); } }
450
13.548387
56
java
z3
z3-master/src/api/java/Optimize.java
/** Copyright (c) 2015 Microsoft Corporation Module Name: Optimize.java Abstract: Z3 Java API: Optimizes Author: Nikolaj Bjorner (nbjorner) 2015-07-16 Notes: **/ package com.microsoft.z3; import com.microsoft.z3.enumerations.Z3_lbool; /** * Object for managing optimization context **/ @SuppressWarnings("unchecked") public class Optimize extends Z3Object { /** * A string that describes all available optimize solver parameters. **/ public String getHelp() { return Native.optimizeGetHelp(getContext().nCtx(), getNativeObject()); } /** * Sets the optimize solver parameters. * * @throws Z3Exception **/ public void setParameters(Params value) { Native.optimizeSetParams(getContext().nCtx(), getNativeObject(), value.getNativeObject()); } /** * Retrieves parameter descriptions for Optimize solver. **/ public ParamDescrs getParameterDescriptions() { return new ParamDescrs(getContext(), Native.optimizeGetParamDescrs(getContext().nCtx(), getNativeObject())); } /** * Assert a constraint (or multiple) into the optimize solver. **/ public void Assert(Expr<BoolSort> ... constraints) { getContext().checkContextMatch(constraints); for (Expr<BoolSort> a : constraints) { Native.optimizeAssert(getContext().nCtx(), getNativeObject(), a.getNativeObject()); } } /** * Alias for Assert. **/ public void Add(Expr<BoolSort> ... constraints) { Assert(constraints); } /** * Assert a constraint into the optimizer, and track it (in the unsat) core * using the Boolean constant p. * * Remarks: * This API is an alternative to {@link #check} with assumptions for * extracting unsat cores. * Both APIs can be used in the same solver. The unsat core will contain a * combination * of the Boolean variables provided using {@link #assertAndTrack} * and the Boolean literals * provided using {@link #check} with assumptions. */ public void AssertAndTrack(Expr<BoolSort> constraint, Expr<BoolSort> p) { getContext().checkContextMatch(constraint); getContext().checkContextMatch(p); Native.optimizeAssertAndTrack(getContext().nCtx(), getNativeObject(), constraint.getNativeObject(), p.getNativeObject()); } /** * Handle to objectives returned by objective functions. **/ public static class Handle<R extends Sort> { private final Optimize opt; private final int handle; Handle(Optimize opt, int h) { this.opt = opt; this.handle = h; } /** * Retrieve a lower bound for the objective handle. **/ public Expr<R> getLower() { return opt.GetLower(handle); } /** * Retrieve an upper bound for the objective handle. **/ public Expr<R> getUpper() { return opt.GetUpper(handle); } /** * @return a triple representing the upper bound of the objective handle. * * The triple contains values {@code inf, value, eps}, * where the objective value is unbounded iff {@code inf} is non-zero, * and otherwise is represented by the expression {@code value + eps * EPSILON}, * where {@code EPSILON} is an arbitrarily small real number. */ public Expr<?>[] getUpperAsVector() { return opt.GetUpperAsVector(handle); } /** * @return a triple representing the upper bound of the objective handle. * * <p>See {@link #getUpperAsVector()} for triple semantics. */ public Expr<?>[] getLowerAsVector() { return opt.GetLowerAsVector(handle); } /** * Retrieve the value of an objective. **/ public Expr<R> getValue() { return getLower(); } /** * Print a string representation of the handle. **/ @Override public String toString() { return getValue().toString(); } } /** * Assert soft constraint * * Return an objective which associates with the group of constraints. * **/ public Handle<?> AssertSoft(Expr<BoolSort> constraint, int weight, String group) { return AssertSoft(constraint, Integer.toString(weight), group); } /** * Assert soft constraint * * Return an objective which associates with the group of constraints. * **/ public Handle<?> AssertSoft(Expr<BoolSort> constraint, String weight, String group) { getContext().checkContextMatch(constraint); Symbol s = getContext().mkSymbol(group); return new Handle<>(this, Native.optimizeAssertSoft(getContext().nCtx(), getNativeObject(), constraint.getNativeObject(), weight, s.getNativeObject())); } /** * Check satisfiability of asserted constraints. * Produce a model that (when the objectives are bounded and * don't use strict inequalities) meets the objectives. **/ public Status Check(Expr<BoolSort>... assumptions) { Z3_lbool r; if (assumptions == null) { r = Z3_lbool.fromInt( Native.optimizeCheck( getContext().nCtx(), getNativeObject(), 0, null)); } else { r = Z3_lbool.fromInt( Native.optimizeCheck( getContext().nCtx(), getNativeObject(), assumptions.length, AST.arrayToNative(assumptions))); } switch (r) { case Z3_L_TRUE: return Status.SATISFIABLE; case Z3_L_FALSE: return Status.UNSATISFIABLE; default: return Status.UNKNOWN; } } /** * Creates a backtracking point. **/ public void Push() { Native.optimizePush(getContext().nCtx(), getNativeObject()); } /** * Backtrack one backtracking point. * * Note that an exception is thrown if Pop is called without a corresponding Push. **/ public void Pop() { Native.optimizePop(getContext().nCtx(), getNativeObject()); } /** * The model of the last Check. * * The result is null if Check was not invoked before, * if its results was not SATISFIABLE, or if model production is not enabled. **/ public Model getModel() { long x = Native.optimizeGetModel(getContext().nCtx(), getNativeObject()); if (x == 0) { return null; } else { return new Model(getContext(), x); } } /** * The unsat core of the last {@code Check}. * Remarks: The unsat core * is a subset of {@code Assumptions} The result is empty if * {@code Check} was not invoked before, if its results was not * {@code UNSATISFIABLE}, or if core production is disabled. * * @throws Z3Exception **/ public BoolExpr[] getUnsatCore() { ASTVector core = new ASTVector(getContext(), Native.optimizeGetUnsatCore(getContext().nCtx(), getNativeObject())); return core.ToBoolExprArray(); } /** * Declare an arithmetical maximization objective. * Return a handle to the objective. The handle is used as * to retrieve the values of objectives after calling Check. **/ public <R extends Sort> Handle<R> MkMaximize(Expr<R> e) { return new Handle<>(this, Native.optimizeMaximize(getContext().nCtx(), getNativeObject(), e.getNativeObject())); } /** * Declare an arithmetical minimization objective. * Similar to MkMaximize. **/ public <R extends Sort> Handle<R> MkMinimize(Expr<R> e) { return new Handle<>(this, Native.optimizeMinimize(getContext().nCtx(), getNativeObject(), e.getNativeObject())); } /** * Retrieve a lower bound for the objective handle. **/ private <R extends Sort> Expr<R> GetLower(int index) { return (Expr<R>) Expr.create(getContext(), Native.optimizeGetLower(getContext().nCtx(), getNativeObject(), index)); } /** * Retrieve an upper bound for the objective handle. **/ private <R extends Sort> Expr<R> GetUpper(int index) { return (Expr<R>) Expr.create(getContext(), Native.optimizeGetUpper(getContext().nCtx(), getNativeObject(), index)); } /** * @return Triple representing the upper bound for the objective handle. * * <p>See {@link Handle#getUpperAsVector}. */ private Expr<?>[] GetUpperAsVector(int index) { return unpackObjectiveValueVector( Native.optimizeGetUpperAsVector( getContext().nCtx(), getNativeObject(), index ) ); } /** * @return Triple representing the upper bound for the objective handle. * * <p>See {@link Handle#getLowerAsVector}. */ private Expr<?>[] GetLowerAsVector(int index) { return unpackObjectiveValueVector( Native.optimizeGetLowerAsVector( getContext().nCtx(), getNativeObject(), index ) ); } private Expr<?>[] unpackObjectiveValueVector(long nativeVec) { ASTVector vec = new ASTVector( getContext(), nativeVec ); return new Expr[] { (Expr<?>) vec.get(0), (Expr<?>) vec.get(1), (Expr<?>) vec.get(2) }; } /** * Return a string the describes why the last to check returned unknown **/ public String getReasonUnknown() { return Native.optimizeGetReasonUnknown(getContext().nCtx(), getNativeObject()); } /** * Print the context to a String (SMT-LIB parseable benchmark). **/ @Override public String toString() { return Native.optimizeToString(getContext().nCtx(), getNativeObject()); } /** * Parse an SMT-LIB2 file with optimization objectives and constraints. * The parsed constraints and objectives are added to the optimization context. */ public void fromFile(String file) { Native.optimizeFromFile(getContext().nCtx(), getNativeObject(), file); } /** * Similar to FromFile. Instead it takes as argument a string. */ public void fromString(String s) { Native.optimizeFromString(getContext().nCtx(), getNativeObject(), s); } /** * The set of asserted formulas. */ public BoolExpr[] getAssertions() { ASTVector assertions = new ASTVector(getContext(), Native.optimizeGetAssertions(getContext().nCtx(), getNativeObject())); return assertions.ToBoolExprArray(); } /** * The set of asserted formulas. */ public Expr<?>[] getObjectives() { ASTVector objectives = new ASTVector(getContext(), Native.optimizeGetObjectives(getContext().nCtx(), getNativeObject())); return objectives.ToExprArray(); } /** * Optimize statistics. **/ public Statistics getStatistics() { return new Statistics(getContext(), Native.optimizeGetStatistics(getContext().nCtx(), getNativeObject())); } Optimize(Context ctx, long obj) throws Z3Exception { super(ctx, obj); } Optimize(Context ctx) throws Z3Exception { super(ctx, Native.mkOptimize(ctx.nCtx())); } @Override void incRef() { Native.optimizeIncRef(getContext().nCtx(), getNativeObject()); } @Override void addToReferenceQueue() { getContext().getOptimizeDRQ().storeReference(getContext(), this); } }
12,035
27.187354
160
java
z3
z3-master/src/api/java/OptimizeDecRefQueue.java
/** Copyright (c) 2012-2015 Microsoft Corporation Module Name: OptimizeDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; class OptimizeDecRefQueue extends IDecRefQueue<Optimize> { public OptimizeDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.optimizeDecRef(ctx.nCtx(), obj); } };
466
14.064516
58
java
z3
z3-master/src/api/java/ParamDescrs.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: ParamDescrs.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import com.microsoft.z3.enumerations.Z3_param_kind; /** * A ParamDescrs describes a set of parameters. **/ public class ParamDescrs extends Z3Object { /** * validate a set of parameters. **/ public void validate(Params p) { Native.paramsValidate(getContext().nCtx(), p.getNativeObject(), getNativeObject()); } /** * Retrieve kind of parameter. **/ public Z3_param_kind getKind(Symbol name) { return Z3_param_kind.fromInt(Native.paramDescrsGetKind( getContext().nCtx(), getNativeObject(), name.getNativeObject())); } /** * Retrieve documentation of parameter. **/ public String getDocumentation(Symbol name) { return Native.paramDescrsGetDocumentation(getContext().nCtx(), getNativeObject(), name.getNativeObject()); } /** * Retrieve all names of parameters. * * @throws Z3Exception **/ public Symbol[] getNames() { int sz = Native.paramDescrsSize(getContext().nCtx(), getNativeObject()); Symbol[] names = new Symbol[sz]; for (int i = 0; i < sz; ++i) { names[i] = Symbol.create(getContext(), Native.paramDescrsGetName( getContext().nCtx(), getNativeObject(), i)); } return names; } /** * The size of the ParamDescrs. **/ public int size() { return Native.paramDescrsSize(getContext().nCtx(), getNativeObject()); } /** * Retrieves a string representation of the ParamDescrs. **/ @Override public String toString() { return Native.paramDescrsToString(getContext().nCtx(), getNativeObject()); } ParamDescrs(Context ctx, long obj) { super(ctx, obj); } @Override void incRef() { Native.paramDescrsIncRef(getContext().nCtx(), getNativeObject()); } @Override void addToReferenceQueue() { getContext().getParamDescrsDRQ().storeReference(getContext(), this); } }
2,263
20.980583
115
java
z3
z3-master/src/api/java/ParamDescrsDecRefQueue.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: ParamDescrsDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; class ParamDescrsDecRefQueue extends IDecRefQueue<ParamDescrs> { public ParamDescrsDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.paramDescrsDecRef(ctx.nCtx(), obj); } }
484
14.15625
64
java
z3
z3-master/src/api/java/Params.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Params.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * A ParameterSet represents a configuration in the form of Symbol/value pairs. **/ public class Params extends Z3Object { /** * Adds a parameter setting. **/ public void add(Symbol name, boolean value) { Native.paramsSetBool(getContext().nCtx(), getNativeObject(), name.getNativeObject(), (value)); } /** * Adds a parameter setting. **/ public void add(Symbol name, double value) { Native.paramsSetDouble(getContext().nCtx(), getNativeObject(), name.getNativeObject(), value); } /** * Adds a parameter setting. **/ public void add(Symbol name, String value) { Native.paramsSetSymbol(getContext().nCtx(), getNativeObject(), name.getNativeObject(), getContext().mkSymbol(value).getNativeObject()); } /** * Adds a parameter setting. **/ public void add(Symbol name, Symbol value) { Native.paramsSetSymbol(getContext().nCtx(), getNativeObject(), name.getNativeObject(), value.getNativeObject()); } /** * Adds a parameter setting. **/ public void add(String name, boolean value) { Native.paramsSetBool(getContext().nCtx(), getNativeObject(), getContext().mkSymbol(name).getNativeObject(), value); } /** * Adds a parameter setting. **/ public void add(String name, int value) { Native.paramsSetUint(getContext().nCtx(), getNativeObject(), getContext() .mkSymbol(name).getNativeObject(), value); } /** * Adds a parameter setting. **/ public void add(String name, double value) { Native.paramsSetDouble(getContext().nCtx(), getNativeObject(), getContext() .mkSymbol(name).getNativeObject(), value); } /** * Adds a parameter setting. **/ public void add(String name, Symbol value) { Native.paramsSetSymbol(getContext().nCtx(), getNativeObject(), getContext() .mkSymbol(name).getNativeObject(), value.getNativeObject()); } /** * Adds a parameter setting. **/ public void add(String name, String value) { Native.paramsSetSymbol(getContext().nCtx(), getNativeObject(), getContext().mkSymbol(name).getNativeObject(), getContext().mkSymbol(value).getNativeObject()); } /** * A string representation of the parameter set. **/ @Override public String toString() { return Native.paramsToString(getContext().nCtx(), getNativeObject()); } Params(Context ctx) { super(ctx, Native.mkParams(ctx.nCtx())); } @Override void incRef() { Native.paramsIncRef(getContext().nCtx(), getNativeObject()); } @Override void addToReferenceQueue() { getContext().getParamsDRQ().storeReference(getContext(), this); } }
3,202
22.551471
83
java
z3
z3-master/src/api/java/ParamsDecRefQueue.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: ParamDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; class ParamsDecRefQueue extends IDecRefQueue<Params> { public ParamsDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.paramsDecRef(ctx.nCtx(), obj); } }
454
13.677419
56
java
z3
z3-master/src/api/java/Pattern.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Pattern.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Patterns comprise a list of terms. The list should be non-empty. If the list * comprises of more than one term, it is also called a multi-pattern. **/ public class Pattern extends AST { /** * The number of terms in the pattern. **/ public int getNumTerms() { return Native.getPatternNumTerms(getContext().nCtx(), getNativeObject()); } /** * The terms in the pattern. * * @throws Z3Exception **/ public Expr<?>[] getTerms() { int n = getNumTerms(); Expr<?>[] res = new Expr[n]; for (int i = 0; i < n; i++) res[i] = Expr.create(getContext(), Native.getPattern(getContext().nCtx(), getNativeObject(), i)); return res; } /** * A string representation of the pattern. **/ @Override public String toString() { return Native.patternToString(getContext().nCtx(), getNativeObject()); } Pattern(Context ctx, long obj) { super(ctx, obj); } }
1,246
18.484375
82
java
z3
z3-master/src/api/java/Probe.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Probe.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Probes are used to inspect a goal (aka problem) and collect information that * may be used to decide which solver and/or preprocessing step will be used. * The complete list of probes may be obtained using the procedures * {@code Context.NumProbes} and {@code Context.ProbeNames}. It may * also be obtained using the command {@code (help-tactic)} in the SMT 2.0 * front-end. **/ public class Probe extends Z3Object { /** * Execute the probe over the goal. * * @return A probe always produce a double value. "Boolean" probes return * 0.0 for false, and a value different from 0.0 for true. * @throws Z3Exception **/ public double apply(Goal g) { getContext().checkContextMatch(g); return Native.probeApply(getContext().nCtx(), getNativeObject(), g.getNativeObject()); } Probe(Context ctx, long obj) { super(ctx, obj); } Probe(Context ctx, String name) { super(ctx, Native.mkProbe(ctx.nCtx(), name)); } @Override void incRef() { Native.probeIncRef(getContext().nCtx(), getNativeObject()); } @Override void addToReferenceQueue() { getContext().getProbeDRQ().storeReference(getContext(), this); } }
1,483
22.935484
79
java
z3
z3-master/src/api/java/ProbeDecRefQueue.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: ProbeDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; class ProbeDecRefQueue extends IDecRefQueue<Probe> { public ProbeDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.probeDecRef(ctx.nCtx(), obj); } };
455
12.818182
56
java
z3
z3-master/src/api/java/Quantifier.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Quantifier.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import com.microsoft.z3.enumerations.Z3_ast_kind; /** * Quantifier expressions. **/ public class Quantifier extends BoolExpr { /** * Indicates whether the quantifier is universal. **/ public boolean isUniversal() { return Native.isQuantifierForall(getContext().nCtx(), getNativeObject()); } /** * Indicates whether the quantifier is existential. **/ public boolean isExistential() { return Native.isQuantifierExists(getContext().nCtx(), getNativeObject()); } /** * The weight of the quantifier. **/ public int getWeight() { return Native.getQuantifierWeight(getContext().nCtx(), getNativeObject()); } /** * The number of patterns. **/ public int getNumPatterns() { return Native .getQuantifierNumPatterns(getContext().nCtx(), getNativeObject()); } /** * The patterns. * * @throws Z3Exception **/ public Pattern[] getPatterns() { int n = getNumPatterns(); Pattern[] res = new Pattern[n]; for (int i = 0; i < n; i++) res[i] = new Pattern(getContext(), Native.getQuantifierPatternAst( getContext().nCtx(), getNativeObject(), i)); return res; } /** * The number of no-patterns. **/ public int getNumNoPatterns() { return Native.getQuantifierNumNoPatterns(getContext().nCtx(), getNativeObject()); } /** * The no-patterns. * * @throws Z3Exception **/ public Pattern[] getNoPatterns() { int n = getNumNoPatterns(); Pattern[] res = new Pattern[n]; for (int i = 0; i < n; i++) res[i] = new Pattern(getContext(), Native.getQuantifierNoPatternAst( getContext().nCtx(), getNativeObject(), i)); return res; } /** * The number of bound variables. **/ public int getNumBound() { return Native.getQuantifierNumBound(getContext().nCtx(), getNativeObject()); } /** * The symbols for the bound variables. * * @throws Z3Exception **/ public Symbol[] getBoundVariableNames() { int n = getNumBound(); Symbol[] res = new Symbol[n]; for (int i = 0; i < n; i++) res[i] = Symbol.create(getContext(), Native.getQuantifierBoundName( getContext().nCtx(), getNativeObject(), i)); return res; } /** * The sorts of the bound variables. * * @throws Z3Exception **/ public Sort[] getBoundVariableSorts() { int n = getNumBound(); Sort[] res = new Sort[n]; for (int i = 0; i < n; i++) res[i] = Sort.create(getContext(), Native.getQuantifierBoundSort( getContext().nCtx(), getNativeObject(), i)); return res; } /** * The body of the quantifier. * * @throws Z3Exception **/ public BoolExpr getBody() { return (BoolExpr) Expr.create(getContext(), Native.getQuantifierBody(getContext() .nCtx(), getNativeObject())); } /** * Translates (copies) the quantifier to the Context {@code ctx}. * * @param ctx A context * * @return A copy of the quantifier which is associated with {@code ctx} * @throws Z3Exception on error **/ public Quantifier translate(Context ctx) { return (Quantifier) super.translate(ctx); } /** * Create a quantified expression. * * @param ctx Context to create the quantifier on. * @param isForall Quantifier type. * @param sorts Sorts of bound variables. * @param names Names of bound variables * @param body Body of quantifier * @param weight Weight used to indicate priority for quantifier instantiation * @param patterns Nullable patterns * @param noPatterns Nullable noPatterns * @param quantifierID Nullable quantifierID * @param skolemID Nullable skolemID */ public static Quantifier of( Context ctx, boolean isForall, Sort[] sorts, Symbol[] names, Expr<BoolSort> body, int weight, Pattern[] patterns, Expr<?>[] noPatterns, Symbol quantifierID, Symbol skolemID) { ctx.checkContextMatch(patterns); ctx.checkContextMatch(noPatterns); ctx.checkContextMatch(sorts); ctx.checkContextMatch(names); ctx.checkContextMatch(body); if (sorts.length != names.length) { throw new Z3Exception( "Number of sorts does not match number of names"); } long nativeObj; if (noPatterns == null && quantifierID == null && skolemID == null) { nativeObj = Native.mkQuantifier(ctx.nCtx(), (isForall), weight, AST.arrayLength(patterns), AST .arrayToNative(patterns), AST.arrayLength(sorts), AST .arrayToNative(sorts), Symbol.arrayToNative(names), body .getNativeObject()); } else { nativeObj = Native.mkQuantifierEx(ctx.nCtx(), (isForall), weight, AST.getNativeObject(quantifierID), AST.getNativeObject(skolemID), AST.arrayLength(patterns), AST.arrayToNative(patterns), AST.arrayLength(noPatterns), AST.arrayToNative(noPatterns), AST.arrayLength(sorts), AST.arrayToNative(sorts), Symbol.arrayToNative(names), body.getNativeObject()); } return new Quantifier(ctx, nativeObj); } /** * @param ctx Context to create the quantifier on. * @param isForall Quantifier type. * @param bound Bound variables. * @param body Body of the quantifier. * @param weight Weight. * @param patterns Nullable array of patterns. * @param noPatterns Nullable array of noPatterns. * @param quantifierID Nullable quantifier identifier. * @param skolemID Nullable skolem identifier. */ public static Quantifier of(Context ctx, boolean isForall, Expr<?>[] bound, Expr<BoolSort> body, int weight, Pattern[] patterns, Expr<?>[] noPatterns, Symbol quantifierID, Symbol skolemID) { ctx.checkContextMatch(noPatterns); ctx.checkContextMatch(patterns); ctx.checkContextMatch(body); long nativeObj; if (noPatterns == null && quantifierID == null && skolemID == null) { nativeObj = Native.mkQuantifierConst(ctx.nCtx(), isForall, weight, AST.arrayLength(bound), AST.arrayToNative(bound), AST.arrayLength(patterns), AST.arrayToNative(patterns), body.getNativeObject()); } else { nativeObj = Native.mkQuantifierConstEx(ctx.nCtx(), isForall, weight, AST.getNativeObject(quantifierID), AST.getNativeObject(skolemID), AST.arrayLength(bound), AST.arrayToNative(bound), AST.arrayLength(patterns), AST.arrayToNative(patterns), AST.arrayLength(noPatterns), AST.arrayToNative(noPatterns), body.getNativeObject()); } return new Quantifier(ctx, nativeObj); } Quantifier(Context ctx, long obj) { super(ctx, obj); } @Override void checkNativeObject(long obj) { if (Native.getAstKind(getContext().nCtx(), obj) != Z3_ast_kind.Z3_QUANTIFIER_AST .toInt()) { throw new Z3Exception("Underlying object is not a quantifier"); } super.checkNativeObject(obj); } }
7,951
29.584615
106
java
z3
z3-master/src/api/java/RatNum.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: RatNum.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import java.math.BigInteger; /** * Rational Numerals **/ public class RatNum extends RealExpr { /** * The numerator of a rational numeral. **/ public IntNum getNumerator() { return new IntNum(getContext(), Native.getNumerator(getContext().nCtx(), getNativeObject())); } /** * The denominator of a rational numeral. **/ public IntNum getDenominator() { return new IntNum(getContext(), Native.getDenominator(getContext().nCtx(), getNativeObject())); } /** * Converts the numerator of the rational to a BigInteger **/ public BigInteger getBigIntNumerator() { IntNum n = getNumerator(); return new BigInteger(n.toString()); } /** * Converts the denominator of the rational to a BigInteger **/ public BigInteger getBigIntDenominator() { IntNum n = getDenominator(); return new BigInteger(n.toString()); } /** * Returns a string representation in decimal notation. * Remarks: The result * has at most {@code precision} decimal places. **/ public String toDecimalString(int precision) { return Native.getNumeralDecimalString(getContext().nCtx(), getNativeObject(), precision); } /** * Returns a string representation of the numeral. **/ @Override public String toString() { return Native.getNumeralString(getContext().nCtx(), getNativeObject()); } RatNum(Context ctx, long obj) { super(ctx, obj); } }
1,809
19.804598
85
java
z3
z3-master/src/api/java/ReExpr.java
/** Copyright (c) 2012-2016 Microsoft Corporation Module Name: ReExpr.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Re expressions **/ public class ReExpr<R extends Sort> extends Expr<ReSort<R>> { /** * Constructor for ReExpr * @throws Z3Exception on error **/ ReExpr(Context ctx, long obj) { super(ctx, obj); } }
453
12.352941
59
java
z3
z3-master/src/api/java/ReSort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: ReSort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * A Regular expression sort **/ public class ReSort<R extends Sort> extends Sort { ReSort(Context ctx, long obj) { super(ctx, obj); } }
370
11.366667
56
java
z3
z3-master/src/api/java/RealExpr.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: RealExpr.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Real expressions **/ public class RealExpr extends ArithExpr<RealSort> { /** * Constructor for RealExpr **/ RealExpr(Context ctx, long obj) { super(ctx, obj); } }
415
11.606061
56
java
z3
z3-master/src/api/java/RealSort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: RealSort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * A real sort **/ public class RealSort extends ArithSort { RealSort(Context ctx, long obj) { super(ctx, obj); } RealSort(Context ctx) { super(ctx, Native.mkRealSort(ctx.nCtx())); } }
441
11.628571
56
java
z3
z3-master/src/api/java/RelationSort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: RelationSort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Relation sorts. **/ public class RelationSort extends Sort { /** * The arity of the relation sort. **/ public int getArity() { return Native.getRelationArity(getContext().nCtx(), getNativeObject()); } /** * The sorts of the columns of the relation sort. * @throws Z3Exception **/ public Sort[] getColumnSorts() { if (m_columnSorts != null) return m_columnSorts; int n = getArity(); Sort[] res = new Sort[n]; for (int i = 0; i < n; i++) res[i] = Sort.create(getContext(), Native.getRelationColumn(getContext() .nCtx(), getNativeObject(), i)); return res; } private Sort[] m_columnSorts = null; RelationSort(Context ctx, long obj) { super(ctx, obj); } }
1,053
17.172414
84
java
z3
z3-master/src/api/java/SeqExpr.java
/** Copyright (c) 2012-2016 Microsoft Corporation Module Name: SeqExpr.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Seq expressions **/ public class SeqExpr<R extends Sort> extends Expr<SeqSort<R>> { /** * Constructor for SeqExpr * @throws Z3Exception on error **/ SeqExpr(Context ctx, long obj) { super(ctx, obj); } }
459
12.529412
61
java
z3
z3-master/src/api/java/SeqSort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: SeqSort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * A Sequence sort **/ public class SeqSort<R extends Sort> extends Sort { SeqSort(Context ctx, long obj) { super(ctx, obj); } }
364
10.774194
56
java
z3
z3-master/src/api/java/SetSort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: SetSort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Set sorts. **/ public class SetSort<D extends Sort> extends ArraySort<D, BoolSort> { SetSort(Context ctx, long obj) { super(ctx, obj); } SetSort(Context ctx, D ty) { super(ctx, Native.mkSetSort(ctx.nCtx(), ty.getNativeObject())); } }
492
13.085714
71
java
z3
z3-master/src/api/java/Simplifier.java
/*++ Copyright (c) 2012 Microsoft Corporation Module Name: Simplifiers.cs Abstract: Z3 Managed API: Simplifiers Author: Christoph Wintersteiger (cwinter) 2012-03-21 --*/ package com.microsoft.z3; public class Simplifier extends Z3Object { /* * A string containing a description of parameters accepted by the simplifier. */ public String getHelp() { return Native.simplifierGetHelp(getContext().nCtx(), getNativeObject()); } /* * Retrieves parameter descriptions for Simplifiers. */ public ParamDescrs getParameterDescriptions() { return new ParamDescrs(getContext(), Native.simplifierGetParamDescrs(getContext().nCtx(), getNativeObject())); } Simplifier(Context ctx, long obj) { super(ctx, obj); } Simplifier(Context ctx, String name) { super(ctx, Native.mkSimplifier(ctx.nCtx(), name)); } @Override void incRef() { Native.simplifierIncRef(getContext().nCtx(), getNativeObject()); } @Override void addToReferenceQueue() { getContext().getSimplifierDRQ().storeReference(getContext(), this); } }
1,136
18.603448
112
java
z3
z3-master/src/api/java/SimplifierDecRefQueue.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: SimplifierDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; class SimplifierDecRefQueue extends IDecRefQueue<Simplifier> { public SimplifierDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.simplifierDecRef(ctx.nCtx(), obj); } }
479
14
62
java
z3
z3-master/src/api/java/Solver.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Solver.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import com.microsoft.z3.enumerations.Z3_lbool; import java.util.*; /** * Solvers. **/ @SuppressWarnings("unchecked") public class Solver extends Z3Object { /** * A string that describes all available solver parameters. **/ public String getHelp() { return Native.solverGetHelp(getContext().nCtx(), getNativeObject()); } /** * Sets the solver parameters. * * @throws Z3Exception **/ public void setParameters(Params value) { getContext().checkContextMatch(value); Native.solverSetParams(getContext().nCtx(), getNativeObject(), value.getNativeObject()); } /** * Retrieves parameter descriptions for solver. * * @throws Z3Exception **/ public ParamDescrs getParameterDescriptions() { return new ParamDescrs(getContext(), Native.solverGetParamDescrs( getContext().nCtx(), getNativeObject())); } /** * The current number of backtracking points (scopes). * @see #pop * @see #push **/ public int getNumScopes() { return Native .solverGetNumScopes(getContext().nCtx(), getNativeObject()); } /** * Creates a backtracking point. * @see #pop **/ public void push() { Native.solverPush(getContext().nCtx(), getNativeObject()); } /** * Backtracks one backtracking point. * Remarks: . **/ public void pop() { pop(1); } /** * Backtracks {@code n} backtracking points. * Remarks: Note that * an exception is thrown if {@code n} is not smaller than * {@code NumScopes} * @see #push **/ public void pop(int n) { Native.solverPop(getContext().nCtx(), getNativeObject(), n); } /** * Resets the Solver. * Remarks: This removes all assertions from the * solver. **/ public void reset() { Native.solverReset(getContext().nCtx(), getNativeObject()); } /** * Interrupt the execution of the solver object. * Remarks: This ensures that the interrupt applies only * to the given solver object and it applies only if it is running. **/ public void interrupt() { Native.solverInterrupt(getContext().nCtx(), getNativeObject()); } /** * Assert a multiple constraints into the solver. * * @throws Z3Exception **/ public void add(Expr<BoolSort>... constraints) { getContext().checkContextMatch(constraints); for (Expr<BoolSort> a : constraints) { Native.solverAssert(getContext().nCtx(), getNativeObject(), a.getNativeObject()); } } /** * Assert multiple constraints into the solver, and track them (in the * unsat) core * using the Boolean constants in ps. * * Remarks: * This API is an alternative to {@link #check()} with assumptions for * extracting unsat cores. * Both APIs can be used in the same solver. The unsat core will contain a * combination * of the Boolean variables provided using {@code #assertAndTrack} * and the Boolean literals * provided using {@link #check()} with assumptions. **/ public void assertAndTrack(Expr<BoolSort>[] constraints, Expr<BoolSort>[] ps) { getContext().checkContextMatch(constraints); getContext().checkContextMatch(ps); if (constraints.length != ps.length) { throw new Z3Exception("Argument size mismatch"); } for (int i = 0; i < constraints.length; i++) { Native.solverAssertAndTrack(getContext().nCtx(), getNativeObject(), constraints[i].getNativeObject(), ps[i].getNativeObject()); } } /** * Assert a constraint into the solver, and track it (in the unsat) core * using the Boolean constant p. * * Remarks: * This API is an alternative to {@link #check} with assumptions for * extracting unsat cores. * Both APIs can be used in the same solver. The unsat core will contain a * combination * of the Boolean variables provided using {@link #assertAndTrack} * and the Boolean literals * provided using {@link #check} with assumptions. */ public void assertAndTrack(Expr<BoolSort> constraint, Expr<BoolSort> p) { getContext().checkContextMatch(constraint); getContext().checkContextMatch(p); Native.solverAssertAndTrack(getContext().nCtx(), getNativeObject(), constraint.getNativeObject(), p.getNativeObject()); } /// <summary> /// Load solver assertions from a file. /// </summary> public void fromFile(String file) { Native.solverFromFile(getContext().nCtx(), getNativeObject(), file); } /// <summary> /// Load solver assertions from a string. /// </summary> public void fromString(String str) { Native.solverFromString(getContext().nCtx(), getNativeObject(), str); } /** * The number of assertions in the solver. * * @throws Z3Exception **/ public int getNumAssertions() { ASTVector assrts = new ASTVector(getContext(), Native.solverGetAssertions(getContext().nCtx(), getNativeObject())); return assrts.size(); } /** * The set of asserted formulas. * * @throws Z3Exception **/ public BoolExpr[] getAssertions() { ASTVector assrts = new ASTVector(getContext(), Native.solverGetAssertions(getContext().nCtx(), getNativeObject())); return assrts.ToBoolExprArray(); } /** * Checks whether the assertions in the solver are consistent or not. * Remarks: * @see #getModel * @see #getUnsatCore * @see #getProof **/ @SafeVarargs public final Status check(Expr<BoolSort>... assumptions) { Z3_lbool r; if (assumptions == null) { r = Z3_lbool.fromInt(Native.solverCheck(getContext().nCtx(), getNativeObject())); } else { r = Z3_lbool.fromInt(Native.solverCheckAssumptions(getContext() .nCtx(), getNativeObject(), assumptions.length, AST .arrayToNative(assumptions))); } return lboolToStatus(r); } /** * Checks whether the assertions in the solver are consistent or not. * Remarks: * @see #getModel * @see #getUnsatCore * @see #getProof **/ @SuppressWarnings("rawtypes") public Status check() { return check((Expr[]) null); } /** * Retrieve fixed assignments to the set of variables in the form of consequences. * Each consequence is an implication of the form * * relevant-assumptions Implies variable = value * * where the relevant assumptions is a subset of the assumptions that are passed in * and the equality on the right side of the implication indicates how a variable * is fixed. * */ public Status getConsequences(Expr<BoolSort>[] assumptions, Expr<?>[] variables, List<Expr<BoolSort>> consequences) { ASTVector result = new ASTVector(getContext()); ASTVector asms = new ASTVector(getContext()); ASTVector vars = new ASTVector(getContext()); for (Expr<BoolSort> asm : assumptions) asms.push(asm); for (Expr<?> v : variables) vars.push(v); int r = Native.solverGetConsequences(getContext().nCtx(), getNativeObject(), asms.getNativeObject(), vars.getNativeObject(), result.getNativeObject()); for (int i = 0; i < result.size(); ++i) consequences.add((BoolExpr) Expr.create(getContext(), result.get(i).getNativeObject())); return lboolToStatus(Z3_lbool.fromInt(r)); } /** * The model of the last {@code Check}. * Remarks: The result is * {@code null} if {@code Check} was not invoked before, if its * results was not {@code SATISFIABLE}, or if model production is not * enabled. * * @throws Z3Exception **/ public Model getModel() { long x = Native.solverGetModel(getContext().nCtx(), getNativeObject()); if (x == 0) { return null; } else { return new Model(getContext(), x); } } /** * The proof of the last {@code Check}. * Remarks: The result is * {@code null} if {@code Check} was not invoked before, if its * results was not {@code UNSATISFIABLE}, or if proof production is * disabled. * * @throws Z3Exception **/ public Expr<?> getProof() { long x = Native.solverGetProof(getContext().nCtx(), getNativeObject()); if (x == 0) { return null; } else { return Expr.create(getContext(), x); } } /** * The unsat core of the last {@code Check}. * Remarks: The unsat core * is a subset of {@code Assertions} The result is empty if * {@code Check} was not invoked before, if its results was not * {@code UNSATISFIABLE}, or if core production is disabled. * * @throws Z3Exception **/ public BoolExpr[] getUnsatCore() { ASTVector core = new ASTVector(getContext(), Native.solverGetUnsatCore(getContext().nCtx(), getNativeObject())); return core.ToBoolExprArray(); } /** * A brief justification of why the last call to {@code Check} returned * {@code UNKNOWN}. **/ public String getReasonUnknown() { return Native.solverGetReasonUnknown(getContext().nCtx(), getNativeObject()); } /** * Create a clone of the current solver with respect to{@code ctx}. */ public Solver translate(Context ctx) { return new Solver(ctx, Native.solverTranslate(getContext().nCtx(), getNativeObject(), ctx.nCtx())); } /** * Solver statistics. * * @throws Z3Exception **/ public Statistics getStatistics() { return new Statistics(getContext(), Native.solverGetStatistics( getContext().nCtx(), getNativeObject())); } /** * A string representation of the solver. **/ @Override public String toString() { return Native .solverToString(getContext().nCtx(), getNativeObject()); } /** * convert lifted Boolean to status */ private Status lboolToStatus(Z3_lbool r) { switch (r) { case Z3_L_TRUE: return Status.SATISFIABLE; case Z3_L_FALSE: return Status.UNSATISFIABLE; default: return Status.UNKNOWN; } } Solver(Context ctx, long obj) { super(ctx, obj); } @Override void incRef() { Native.solverIncRef(getContext().nCtx(), getNativeObject()); } @Override void addToReferenceQueue() { getContext().getSolverDRQ().storeReference(getContext(), this); } }
11,277
26.574572
152
java
z3
z3-master/src/api/java/SolverDecRefQueue.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: SolverDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; class SolverDecRefQueue extends IDecRefQueue<Solver> { public SolverDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.solverDecRef(ctx.nCtx(), obj); } }
442
14.821429
56
java
z3
z3-master/src/api/java/Sort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Sort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import com.microsoft.z3.enumerations.Z3_ast_kind; import com.microsoft.z3.enumerations.Z3_sort_kind; /** * The Sort class implements type information for ASTs. **/ public class Sort extends AST { /** * Equality operator for objects of type Sort. **/ @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Sort)) return false; Sort other = (Sort) o; return (getContext().nCtx() == other.getContext().nCtx()) && (Native.isEqSort(getContext().nCtx(), getNativeObject(), other.getNativeObject())); } /** * Hash code generation for Sorts * * @return A hash code **/ public int hashCode() { return super.hashCode(); } /** * Returns a unique identifier for the sort. **/ public int getId() { return Native.getSortId(getContext().nCtx(), getNativeObject()); } /** * The kind of the sort. **/ public Z3_sort_kind getSortKind() { return Z3_sort_kind.fromInt(Native.getSortKind(getContext().nCtx(), getNativeObject())); } /** * The name of the sort **/ public Symbol getName() { return Symbol.create(getContext(), Native.getSortName(getContext().nCtx(), getNativeObject())); } /** * A string representation of the sort. **/ @Override public String toString() { return Native.sortToString(getContext().nCtx(), getNativeObject()); } /** * Translates (copies) the sort to the Context {@code ctx}. * * @param ctx A context * * @return A copy of the sort which is associated with {@code ctx} * @throws Z3Exception on error **/ public Sort translate(Context ctx) { return (Sort) super.translate(ctx); } /** * Sort constructor **/ Sort(Context ctx, long obj) { super(ctx, obj); } @Override void checkNativeObject(long obj) { if (Native.getAstKind(getContext().nCtx(), obj) != Z3_ast_kind.Z3_SORT_AST .toInt()) throw new Z3Exception("Underlying object is not a sort"); super.checkNativeObject(obj); } static Sort create(Context ctx, long obj) { Z3_sort_kind sk = Z3_sort_kind.fromInt(Native.getSortKind(ctx.nCtx(), obj)); switch (sk) { case Z3_ARRAY_SORT: return new ArraySort<>(ctx, obj); case Z3_BOOL_SORT: return new BoolSort(ctx, obj); case Z3_BV_SORT: return new BitVecSort(ctx, obj); case Z3_DATATYPE_SORT: return new DatatypeSort<>(ctx, obj); case Z3_INT_SORT: return new IntSort(ctx, obj); case Z3_REAL_SORT: return new RealSort(ctx, obj); case Z3_UNINTERPRETED_SORT: return new UninterpretedSort(ctx, obj); case Z3_FINITE_DOMAIN_SORT: return new FiniteDomainSort(ctx, obj); case Z3_RELATION_SORT: return new RelationSort(ctx, obj); case Z3_FLOATING_POINT_SORT: return new FPSort(ctx, obj); case Z3_ROUNDING_MODE_SORT: return new FPRMSort(ctx, obj); case Z3_SEQ_SORT: return new SeqSort<>(ctx, obj); case Z3_RE_SORT: return new ReSort<>(ctx, obj); default: throw new Z3Exception("Unknown sort kind"); } } }
3,718
23.467105
95
java
z3
z3-master/src/api/java/Statistics.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Statistics.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Objects of this class track statistical information about solvers. **/ public class Statistics extends Z3Object { /** * Statistical data is organized into pairs of [Key, Entry], where every * Entry is either a {@code DoubleEntry} or a {@code UIntEntry} **/ public class Entry { /** * The key of the entry. **/ public String Key; /** * The uint-value of the entry. **/ public int getUIntValue() { return m_int; } /** * The double-value of the entry. **/ public double getDoubleValue() { return m_double; } /** * True if the entry is uint-valued. **/ public boolean isUInt() { return m_is_int; } /** * True if the entry is double-valued. **/ public boolean isDouble() { return m_is_double; } /** * The string representation of the entry's value. * * @throws Z3Exception **/ public String getValueString() { if (isUInt()) { return Integer.toString(m_int); } else if (isDouble()) { return Double.toString(m_double); } else { throw new Z3Exception("Unknown statistical entry type"); } } /** * The string representation of the Entry. **/ @Override public String toString() { return Key + ": " + getValueString(); } private boolean m_is_int = false; private boolean m_is_double = false; private int m_int = 0; private double m_double = 0.0; Entry(String k, int v) { Key = k; m_is_int = true; m_int = v; } Entry(String k, double v) { Key = k; m_is_double = true; m_double = v; } } /** * A string representation of the statistical data. **/ @Override public String toString() { return Native.statsToString(getContext().nCtx(), getNativeObject()); } /** * The number of statistical data. **/ public int size() { return Native.statsSize(getContext().nCtx(), getNativeObject()); } /** * The data entries. * * @throws Z3Exception **/ public Entry[] getEntries() { int n = size(); Entry[] res = new Entry[n]; for (int i = 0; i < n; i++) { Entry e; String k = Native.statsGetKey(getContext().nCtx(), getNativeObject(), i); if (Native.statsIsUint(getContext().nCtx(), getNativeObject(), i)) { e = new Entry(k, Native.statsGetUintValue(getContext().nCtx(), getNativeObject(), i)); } else if (Native.statsIsDouble(getContext().nCtx(), getNativeObject(), i)) { e = new Entry(k, Native.statsGetDoubleValue(getContext().nCtx(), getNativeObject(), i)); } else { throw new Z3Exception("Unknown data entry value"); } res[i] = e; } return res; } /** * The statistical counters. **/ public String[] getKeys() { int n = size(); String[] res = new String[n]; for (int i = 0; i < n; i++) res[i] = Native.statsGetKey(getContext().nCtx(), getNativeObject(), i); return res; } /** * The value of a particular statistical counter. * Remarks: Returns null if * the key is unknown. * * @throws Z3Exception **/ public Entry get(String key) { int n = size(); Entry[] es = getEntries(); for (int i = 0; i < n; i++) { if (es[i].Key.equals(key)) { return es[i]; } } return null; } Statistics(Context ctx, long obj) { super(ctx, obj); } @Override void incRef() { getContext().getStatisticsDRQ().storeReference(getContext(), this); } @Override void addToReferenceQueue() { Native.statsIncRef(getContext().nCtx(), getNativeObject()); } }
4,611
21.831683
89
java